在运行时以编程方式创建SQL Server数据库

时间:2014-07-29 09:22:11

标签: sql-server vb.net visual-studio-2010 sql-server-2008 visual-studio-2013

我正在创建一个使用sql server 2008数据库的vb .net winform项目。我或多或少完成了项目,但我想稍微调整一下。其中一项调整如下。我在sql server 2008中创建了数据库,但我想知道如何在vb .net项目中以编程方式创建数据库。我在这个问题上搜索了互联网,但对我来说没有什么是清楚的。我是在开始表单中创建数据库还是在单独的类中创建数据库并以我使用数据库的其他形式调用它?任何有关此事的帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

以下代码将帮助您创建名为my_db的数据库和名为customer的数据库中的表。

注意:在评论中给出了必要的解释,请阅读以便澄清

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        //creating and initializing the connection string
        Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False")
        //since we need to create a new database set the Initial Catalog as Master
        //Which means we are creating database under master DB
        Dim myCommand As String //to store the sql command to be executed
        myCommand = "CREATE database my_db" //the command that creates new database
        Dim cmd As SqlCommand = New SqlCommand(myCommand, myConnectionString) // creating command for execution
        Try
            cmd.Connection.Open() //open a connection with cmd
            cmd.ExecuteNonQuery() //Execute the query
            cmd.Connection.Close() //Close the connection
        Catch
            MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
        End Try
        //Creating table to the dynamicaly created database
        Try
            Dim cn As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;Pooling=False")
          //here the connection string is initialized with Initial Catalog as my_db
            Dim sql As String //sql query string
            sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)"
            cmd = New SqlCommand(sql, cn) // create command with connection and query string 
            cmd.Connection.Open()
            cmd.ExecuteNonQuery()
            cmd.Connection.Close()
          Catch
           MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
          End Try
    End Sub