【问题标题】:Create a sql server database programmatically at run time在运行时以编程方式创建 sql server 数据库
【发布时间】:2014-07-29 09:22:11
【问题描述】:

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

【问题讨论】:

  • 我知道如何对数据库进行编码,但我想知道应该将代码放在哪里?它应该在启动表单中还是在单独的类中并从该类中调用数据库?
  • 我个人将它保存在一个单独的项目中。如果您的 WinForms 项目相当大,则创建一个“DataAccess.dll”,然后您所要做的就是调用“GetListOfUsers”或任何其他方法来检索您的数据。 (换句话说,单独的类!)。当然,这也是一种偏好。
  • 好的。所以你的意思是我应该在另一个类中创建数据库并根据需要在表单中调用数据库?如果我在 vb .net 类中以编程方式创建与我在 sql server 中创建的数据库完全相同的数据库,我是否必须更改已有的用于查询现有数据库的代码?或者我可以保持原样吗?

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


【解决方案1】:

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

注意:必要的解释在cmets中给出,请阅读清楚

    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

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多