• Domingo 28 de Abril de 2024, 01:14

Autor Tema:  Elegir Servidor al crear una Base de Datos SQL  (Leído 1652 veces)

HacKreatorz

  • Nuevo Miembro
  • *
  • Mensajes: 2
    • Ver Perfil
    • http://tecnoplanet.co.cc
Elegir Servidor al crear una Base de Datos SQL
« en: Sábado 30 de Enero de 2010, 19:30 »
0
Buenas, estoy creando una aplicación en VB.NET 2008 y necesito que al pulsar un botón se cree una base de datos. Estoy siguiendo un tutorial de otra web. Estoy usando este código, modifiqué bastante el que salía en el tuto y se me quedó así:

Citar
Dim str As String
                Dim myConn As SqlConnection = New SqlConnection("Server=127.0.0.1;" & _
                                                                "uid=sa;pwd=;database=master")
                str = "CREATE DATABASE MyDatabase ON PRIMARY " & _
                      "(NAME = MyDatabase_Data, " & _
                      " FILENAME = 'C:Archivos de programaAllDataBase ManagerBases de Datos'" & nombreBD & "'MyDatabaseData.mdf', " & _
                      " SIZE = 2MB, " & _
                      " MAXSIZE = 10MB, " & _
                      " FILEGROWTH = 10%) " & _
                      " LOG ON " & _
                      "(NAME = MyDatabase_Log, " & _
                      " FILENAME = 'C:Archivos de programaAllDataBase ManagerBases de Datos'" & nombreBD & "' MyDatabaseLog.ldf', " & _
                      " SIZE = 1MB, " & _
                      " MAXSIZE = 5MB, " & _
                      " FILEGROWTH = 10%) "

                Dim myCommand As SqlCommand = New SqlCommand(str, myConn)
                Try
                    myConn.Open()
                    myCommand.ExecuteNonQuery()
                    MessageBox.Show("   B ase de Datos creada correctamente", _
                                    "MyProgram", MessageBoxButtons.OK, _
                                     MessageBoxIcon.Information)
                Catch ex As Exception
                    MessageBox.Show(ex.ToString())
                    LabelInfoBD.Text = "Error al crear la base de datos"
                Finally
                    If (myConn.State = ConnectionState.Open) Then
                        myConn.Close()
                    End If
                End Try
                LabelInfoBD.Refresh()
            End If


No me funciona el código, le doy al botón pero se queda pillado, no se que es lo que está mal, no se si es el servidor que puse que me parece que es uno localhost que es lo que quiero...

agl0809

  • Visitante
Re: Elegir Servidor al crear una Base de Datos SQL
« Respuesta #1 en: Domingo 28 de Febrero de 2010, 18:50 »
0
Estoy seguro de que esta Clase te va a ayudar. Este ejemplo pertenece a un proyecto que he hecho hace poco. La clase se ejecuta en la instalación del programa, previamente añadida a "acciones personalizadas" del proyecto de instalación.

Código: vb.net
  1.  
  2.  
  3. Imports System.ComponentModel
  4. Imports System.Configuration.Install
  5. Imports System.Configuration
  6. Imports System.Data.SqlClient
  7. Imports System.IO
  8. Imports System.Reflection
  9.  
  10. Public Class ActualizaConfig
  11.  
  12.     Public Sub New()
  13.         MyBase.New()
  14.  
  15.         'El Diseñador de componentes requiere esta llamada.
  16.         InitializeComponent()
  17.  
  18.         'Agregue el código de inicialización después de llamar a InitializeComponent
  19.  
  20.     End Sub
  21.  
  22.     Public Overrides Sub Install(ByVal stateSaver As System.Collections.IDictionary)
  23.         MyBase.Install(stateSaver)
  24.         Dim directorio As String = Me.Context.Parameters.Item("directorio")
  25.         Dim servidor As String = Me.Context.Parameters.Item("server")
  26.         Dim execpath As String = String.Format("{0}AplicaOlivar2010.exe", directorio)
  27.         Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(execpath)
  28.         ''
  29.         Dim frm As New ElegirServidor()
  30.         frm.ShowDialog()
  31.         servidor = frm.ComboBox1.SelectedItem
  32.  
  33.         config.ConnectionStrings.ConnectionStrings("Almazara2010Conexion").ConnectionString = "Data source=" _
  34.         & servidor & "; Initial Catalog=master; Integrated Security=True"
  35.         config.Save()
  36.  
  37.         crearBaseDatos(config)
  38.  
  39.     End Sub
  40.  
  41.     Public Sub crearBaseDatos(ByVal config As Configuration)
  42.         Dim conexion As New SqlConnection(config.ConnectionStrings.ConnectionStrings("Almazara2010Conexion").ConnectionString)
  43.         Dim cmd As New SqlCommand("Create Database Almazara2010", conexion)
  44.  
  45.         conexion.Open()
  46.         cmd.ExecuteNonQuery()
  47.         conexion.Close()
  48.         config.ConnectionStrings.ConnectionStrings("Almazara2010Conexion").ConnectionString = config.ConnectionStrings.ConnectionStrings("Almazara2010Conexion").ConnectionString.Replace("master", "Almazara2010")
  49.         config.Save()
  50.         conexion.ConnectionString = config.ConnectionStrings.ConnectionStrings("Almazara2010Conexion").ConnectionString
  51.  
  52.         'Para cambiar la conectionstring segunda
  53.         config.ConnectionStrings.ConnectionStrings("WindowsApplication2.My.MySettings.Almazara2010ConnectionString").ConnectionString = config.ConnectionStrings.ConnectionStrings("Almazara2010Conexion").ConnectionString.Replace("master", "Almazara2010")
  54.         config.Save()
  55.         conexion.ConnectionString = config.ConnectionStrings.ConnectionStrings("WindowsApplication2.My.MySettings.Almazara2010ConnectionString").ConnectionString
  56.  
  57.         'Crear las tablas
  58.         conexion.ConnectionString = config.ConnectionStrings.ConnectionStrings("WindowsApplication2.My.MySettings.Almazara2010ConnectionString").ConnectionString
  59.         Dim Command As New SqlClient.SqlCommand(GetSql("tablas.txt"), conexion)
  60.         Command.Connection.Open()
  61.         Command.ExecuteNonQuery()
  62.         Command.Connection.Close()
  63.  
  64.     End Sub
  65.  
  66.     Private Function GetSql(ByVal Name As String) As String
  67.         Try
  68.  
  69.             ' Gets the current assembly.
  70.             Dim Asm As [Assembly] = [Assembly].GetExecutingAssembly()
  71.  
  72.             ' Resources are named using a fully qualified name.
  73.             Dim strm As Stream = Asm.GetManifestResourceStream( _
  74.               Asm.GetName().Name + "." + Name)
  75.  
  76.             ' Reads the contents of the embedded file.
  77.             Dim reader As StreamReader = New StreamReader(strm)
  78.             Return reader.ReadToEnd()
  79.  
  80.         Catch ex As Exception
  81.             MsgBox("In GetSQL: " & ex.Message)
  82.             Throw ex
  83.         End Try
  84.     End Function
  85.  
  86.  
  87.  

Esta clase se apoya de un formulario muy siemple, que contiene un ComboBox que se rellena de los posibles servidores de DDBB que se encuentren activos en el equipo o en la red.

Código: vb.net
  1.  
  2.  
  3. Imports System.Data.Sql
  4. Imports System.Data.SqlClient
  5.  
  6. Public Class ElegirServidor
  7.  
  8.     Private Sub ElegirServidor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  9.  
  10.  
  11.  
  12.         Dim instancia As SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance
  13.         Dim tabla As DataTable = instancia.GetDataSources()
  14.  
  15.         For Each fila As DataRow In tabla.Rows
  16.             If fila.ItemArray(1).ToString() = String.Empty Then
  17.                 ComboBox1.Items.Add(fila.ItemArray(0).ToString())
  18.             Else
  19.                 ComboBox1.Items.Add(fila.ItemArray(0).ToString() & "\" & fila.ItemArray(1).ToString())
  20.             End If
  21.         Next
  22.     End Sub
  23.  
  24.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  25.         Me.Close()
  26.     End Sub
  27.  
  28.    
  29.     Private Sub ElegirServidor_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
  30.         Media.SystemSounds.Exclamation.Play()
  31.     End Sub
  32. End Class
  33.  
  34.  
  35.  

Espero que te sirva de ayuda, el código funciona correctamente  :good:

HacKreatorz

  • Nuevo Miembro
  • *
  • Mensajes: 2
    • Ver Perfil
    • http://tecnoplanet.co.cc
Re: Elegir Servidor al crear una Base de Datos SQL
« Respuesta #2 en: Miércoles 3 de Marzo de 2010, 07:09 »
0
Muchas gracias por el comentario, ahora mismo estoy en época de exámenes y no voy a poder ponerme a mirarlo pero en cuanto pueda ya te comentaré si me ha funcionado. Gracias ;)