我有一个简单的C#函数应该创建一个名为Database2.mdf的新的Microsoft SQL数据库。简单的函数来创建SQL数据库失败:什么是错的?
我的问题:函数无法创建数据库&我不确定为什么?我从MSDN复制了演示如何创建数据库的代码,但我不确定我的SqlConnection字符串或我的SQLCommand字符串是否正确?
出现的错误是:
{"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}
我的代码:
public static string DEF_DB_NAME = "Database2";
private bool create()
{
Console.WriteLine("populating data");
bool res = false;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE "+DEF_DB_NAME+" ON PRIMARY " +
"(NAME = .\\SQLEXPRESS, " +
"FILENAME = " + DEF_DB_NAME + ".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " + DEF_DB_NAME + "_Log, " +
"FILENAME = " + DEF_DB_NAME + "Log.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
myConn.Open(); // ERROR OCCURS HERE
myCommand.ExecuteNonQuery();
insertDefData(myConn);
myConn.Close();
res = true;
return res;
}
无法打开连接并与查询无关。你可以将'myConn.Open()'移到命令定义的上面,它仍然会发生。 – Fosco 2012-02-18 00:09:45
提供程序:命名管道提供程序是否尝试连接到本地服务器? – 2012-02-18 00:09:50
您是否检查过您的SQL Server Express实例是否在此计算机上运行? – rcdmk 2012-02-18 00:10:20