sql-server - 在运行时以编程方式创建 sql server 数据库

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

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

最佳答案

以下代码将帮助您创建一个名为 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

关于sql-server - 在运行时以编程方式创建 sql server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25011969/

相关文章:

visual-studio - 在 Visual Studio 命令提示符中更改分区

c# - 在 Visual Studio 中运行特定的单元测试

sql-server - 当 where 子句中使用的索引列具有特定值时,Azure sql 查询速度很慢

sql-server - 获得超过 1 个递归 CTE 结果集?

sql-server - sql脚本涵盖所有可能的变量组合?帮助,应用程序,什么?

c# - 如何将其写入 linq to object 查询?

visual-studio-2010 - 无法让 Resharper Test Runner 在 VS 2010 上使用 MS Test

sql - 如何在运行总计达到零的帐户上应用状态

javascript - VB 2010 中等效的 JS eventListener

vb.net - 缺少依赖项时如何避免异常? (WMP控制)