动态创建.mdf / .sdf数据库 [英] Create .mdf/.sdf database dynamically
本文介绍了动态创建.mdf / .sdf数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何用代码创建一个新的.mdf / .sdf数据库?
How can I with "code" create a new .mdf/.sdf database?
我试过这样:
http://support.microsoft.com/kb/307283
它在ConnectionString上失败。因为我没有连接到一个文件,在我创建它之前存在,我怎么才能连接到SQL Express服务器只是创建一个mdf / sdf数据库?
All it does is fail on the ConnectionString. Since I have no connection to a file that exists before I create it, how can I only connect to the SQL Express Server just to create a mdf/sdf database?
I想要能够只连接到服务器并创建文件,从那里可能会更容易创建表等。
I want to be able to just connect to the server and create the file, from there it probably will be easier to create the tables and such.
有任何建议吗? >
Any suggestions?
推荐答案
public static void CreateSqlDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new System.Data.SqlClient.SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
}
}
更改 Catalog = tempdb
到 Catalog = master
,其工作良好
var filename = System.IO.Path.Combine("D:\\", "testdb.mdf");
if (!System.IO.File.Exists(filename))
{
CreateSqlDatabase(filename);
}
这篇关于动态创建.mdf / .sdf数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文