如何在SQL Server中以编程方式创建数据库?

时间:2022-01-02 07:24:51

How can I create a new database from my C# application?

如何从C#应用程序创建新数据库?

I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements.

我假设一旦我创建它,我可以简单地生成连接字符串并连接到它,并发出所有CREATE TABLE语句。

2 个解决方案

#1


13  

KB307283 explains how to create a database using ADO.NET.

KB307283解释了如何使用ADO.NET创建数据库。

From the article:

来自文章:

String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

SqlCommand myCommand = new SqlCommand(str, myConn);
try 
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
}

#2


1  

CREATE DATABASE works

CREATE DATABASE有效

#1


13  

KB307283 explains how to create a database using ADO.NET.

KB307283解释了如何使用ADO.NET创建数据库。

From the article:

来自文章:

String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

SqlCommand myCommand = new SqlCommand(str, myConn);
try 
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
}

#2


1  

CREATE DATABASE works

CREATE DATABASE有效