Spo*_*man 3 mdf sql-server-2012 localdb
如何以编程方式创建localdb .mdf?
可接受的解决方案不包括 visual studio,ssms,aspnet_regsql.
一个天真的解决方案可能看起来像这样:
static void Main(string[] args)
{
using (var con = new SqlConnection(@"Integrated Security=SSPI;Data Source=(LocalDb)\v11.0;AttachDbFilename=test.mdf"))
{
con.Open();
using (var cmd = new SqlCommand("CREATE DATABASE test", con))
{
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但当然,这在SqlConnection.Open中失败并出现错误
尝试为文件test.mdf附加自动命名的数据库失败.存在具有相同名称的数据库,或者无法打开指定的文件,或者它位于UNC共享上.
如果指定的.mdf不存在,则无法连接到数据库.
那么......你怎么创造一个?
不得不将来自Stackoverflow和@AaronBertrand的SQL Server 2012 Express LocalDB入门文章的几个答案拼凑起来
代码假设安装了Dapper.NET:
PM> Install-Package Dapper
程序化创作:
var dbServerName = "SERVER_NAME";
var dbName = "DATABASE_NAME";
var infoResult = SqlLocalDbCommand($"info {dbServerName}");
var needsCreated = infoResult?.Trim().EndsWith($"\"{dbServerName}\" doesn't exist!");
if (needsCreated.GetValueOrDefault(false))
{
var createResult = SqlLocalDbCommand($"create {dbServerName} -s");
var success = createResult?.Trim().EndsWith($"\"{dbServerName}\" started.");
if (false == success)
{
var msg = $"Failed to create database:{Environment.NewLine}{createResult}"
throw new ApplicationException(msg);
}
var master = $@"Server=(localdb)\{dbServerName};Integrated Security=True;"
using (var conn = new SqlConnection(master))
{
var result = conn.Execute($"CREATE DATABASE {dbName}");
}
var @new = $@"Server=(localdb)\{dbServerName};Integrated Security=True;Database={dbName}"
using (var conn = new SqlConnection(@new))
{
//verify i can access my new database
var tables = conn.Query($"SELECT * FROM {dbName}.INFORMATION_SCHEMA.Tables");
}
}
Run Code Online (Sandbox Code Playgroud)
助手(谢谢T30):
/// <summary>
/// Executes a command against SqlLocalDB
/// </summary>
/// <remarks></remarks>
/// <param name="arguments">The arguments to pass to SqlLocalDB.exe</param>
/// <returns></returns>
/// <exception cref="System.ApplicationException">Error returned from process</exception>
private static string SqlLocalDbCommand(string arguments)
{
var process = new Process
{
StartInfo =
{
FileName = "SqlLocalDB",
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
process.Start();
//* Read the output (or the error)
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
var err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
if (err.Exists()) throw new ApplicationException(err); //Is LocalDB installed?
return output;
}
Run Code Online (Sandbox Code Playgroud)
请注意,使用此解决方案,您将看不到mdf文件,我确定它们存在于某个用户文件夹中,但关键是带走的是您将通过连接字符串连接
(localdb)\SERVER_NAME;Integrated Security=True;Database=DATABASE_NAME
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3891 次 |
| 最近记录: |