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

Pas*_*cal 13 c# database sql-server

如何以编程方式创建数据库以及我需要执行此操作的最少信息是什么?

不要"SQL Server管理对象API"建议.

jer*_*enh 25

您可以使用SQL Server管理对象API(请参阅" 创建,更改和删除数据库 "任务):

 var srv = new Server();
 var db = new Database(srv, "mydb");
 db.Create();
Run Code Online (Sandbox Code Playgroud)

有关如何入门的信息在这里.在SQL Server安装期间,您需要安装客户端SDK,SMO程序集位于C:\ Program Files\Microsoft SQL Server\100\SDK\Assemblies

或者,如果您不希望依赖于这些程序集,您也可以使用ADO.Net简单地运行DDL语句(例如,请参阅此问题):

using (var connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "CREATE DATABASE mydb";
    command.ExecuteNonQuery();
}  
Run Code Online (Sandbox Code Playgroud)

显然,您需要一个正确的连接字符串:已知的sql server实例和具有CREATE DATABASE权限的用户.


naw*_*fal 6

来自创作者:

// your connection string
string connectionString = "Server=(local)\\netsdk;uid=sa;pwd=;database=master";

// your query:
var query = GetDbCreationQuery();

var conn = new SqlConnection(connectionString);
var command = new SqlCommand(query, conn);

try
{
    conn.Open();
    command.ExecuteNonQuery();
    MessageBox.Show("Database is created successfully", "MyProgram", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
finally
{
    if ((conn.State == ConnectionState.Open))
    {
        conn.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用默认设置在默认位置创建,只需:

static string GetDbCreationQuery()
{
    // your db name
    string dbName = "MyDatabase";

    // db creation query
    string query = "CREATE DATABASE " + dbName + ";";

    return query;
}
Run Code Online (Sandbox Code Playgroud)

或者,在特定位置创建它:

static string GetDbCreationQuery()
{
    // your db name
    string dbName = "MyDatabase";

    // path to your db files:
    // ensure that the directory exists and you have read write permission.
    string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"), 
                       Path.Combine(Application.StartupPath, dbName + ".ldf") };

    // db creation query:
    // note that the data file and log file have different logical names
    string query = "CREATE DATABASE " + dbName +
        " ON PRIMARY" +
        " (NAME = " + dbName + "_data," +
        " FILENAME = '" + files[0] + "'," +
        " SIZE = 3MB," +
        " MAXSIZE = 10MB," +
        " FILEGROWTH = 10%)" +

        " LOG ON" +
        " (NAME = " + dbName + "_log," +
        " FILENAME = '" + files[1] + "'," +
        " SIZE = 1MB," +
        " MAXSIZE = 5MB," +
        " FILEGROWTH = 10%)" +
        ";";

    return query;
}
Run Code Online (Sandbox Code Playgroud)

即使执行失败,也要再试一次.可能已创建db文件.


Gle*_*enn 5

Create database 'Databasename'
Run Code Online (Sandbox Code Playgroud)

  • 当然这很愚蠢,我只是使用了一个不存在的/虚拟的连接字符串来创建db:P (4认同)