参考如何使用 ADO.NET 和 Visual C# .NET 以编程方式创建 SQL Server 数据库写了一个控制台程序用来创建SQL Server数据库。
原理很简单,首先利用SqlConnection连接master数据库,然后利用SqlCommand执行创建数据库的T-SQL语句。
注意:对于SQL Server 2008 R2,mdf文件的Size应至少大于3MB。
class Program
{
static void Main(string[] args)
{
string exit = string.Empty;
SqlConnection conn = new SqlConnection("Server=localhost;Integrated Security=SSPI;database=master");
conn.Open();
while (exit != "n")
{
Console.WriteLine("Please input your database name: \n");
string dbname = Console.ReadLine().Trim();
string str = string.Format("CREATE DATABASE {0} ON PRIMARY" +
"(NAME = {0}_Data, FILENAME = 'C:\\{0}Data.mdf', " +
"SIZE = 3MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = {0}_Log, FILENAME='C:\\{0}Log.ldf', " +
"SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 10%)", dbname);
using (SqlCommand cmd = new SqlCommand(str, conn))
{
cmd.ExecuteNonQuery();
}
Console.WriteLine("Do you want to continue\n? [y/n]");
exit = Console.ReadLine();
exit = exit.Trim().ToLower();
}
conn.Close();
}
}
本文介绍了一个使用ADO.NET和Visual C#.NET编程方式创建SQL Server数据库的控制台程序。程序通过连接master数据库并执行创建数据库的T-SQL语句来实现。特别关注了SQL Server 2008 R2中mdf文件的大小建议至少为3MB。程序允许用户输入数据库名称,并持续创建多个数据库直至用户选择停止。

1082

被折叠的 条评论
为什么被折叠?



