我是 C# 的新手,我正在尝试以编程方式创建和打开 SQL Server 数据库。
我有一个正在创建的 ASP.NET webapp,在页面加载时它应该从数据库中提取一些数据(如果数据库不存在,应该创建它并使用默认数据填充)。
PS:C# 的 System.Data.SqlClient
使用 MySQL 或 SQLite 还是其他什么东西?
现在我不确定我的代码是否正确创建了 SQL Server 数据库以及我是否正确连接到它。
你能告诉我我的代码是否正确以及我如何改进它吗?
更新:错误是
"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)"}"
我已经在下面的代码中指出了错误发生的位置。
创建 SQL Server 数据库:
// When I run this function no file seems to be created in my project directory?
// Although there is a ASPNETDB sql database file in my App_Data folder so this maybe it
public static string DEF_DB_NAME = "mydb.db"; // is this the correct extension?
private bool populateDbDefData()
{
bool res = false;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE "+DEF_DB_NAME+" ON PRIMARY " +
"(NAME = " + DEF_DB_NAME + "_Data, " +
"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);
try
{
myConn.Open(); // ERROR OCCURS HERE
myCommand.ExecuteNonQuery();
insertDefData(myConn);
}
catch (System.Exception ex)
{
res = false;
}
finally
{
if (myConn.State == ConnectionState.Open)
myConn.Close();
res = true;
}
return res;
}
这是我与 SQL Server 数据库的连接代码:我很确定它无法连接 - 如果我尝试使用变量 conn,它会说连接未打开。这可能意味着我要么无法连接,要么甚至无法在第一时间创建数据库:
private bool connect()
{
bool res = false;
try
{
conn = new SqlConnection("user id=username;" +
"password=password;" +
"Server=localhost;" +
"Trusted_Connection=yes;" +
"database="+DEF_DB_NAME+"; " +
"connection timeout=30");
conn.Open();
return true;
}
catch (Exception e)
{
}
return false;
}
最佳答案
您可能已经弄清楚了,但以防万一人们在这里遇到同样的问题(就像我一样),下面是我如何让这个工作的。
您的错误是没有打开 SqlConnection,因为它没有找到合适的服务器。如果您使用的是 SQL Server Express 版本(就像我一样),您应该像这样设置 SqlConnection 对象:
SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=master;");
一旦您解决了该错误,当您尝试执行查询时,您将在下一行失败。 “文件名”需要用单引号隔开,但是你在扩展名后面只有一个;你之前也需要一个。
另外,那是完整的物理文件路径,它不会使用当前目录上下文,你必须指定一个路径。确保该位置是数据库服务器在运行时可以访问的位置,否则您将抛出 SqlException 并显示如下错误消息:
Directory lookup for the file "...\filename.mdf" failed with the operating system error 5 (Access is denied). CREATE DATABASE failed. Some file names listed could not be created.
我最终使用的代码如下所示:
public static string DB_NAME = "mydb"; //you don't need an extension here, this is the db name not a filename
public static string DB_PATH = "C:\\data\\";
public bool CreateDatabase()
{
bool stat=true;
string sqlCreateDBQuery;
SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=master;");
sqlCreateDBQuery = " CREATE DATABASE "
+ DB_NAME
+ " ON PRIMARY "
+ " (NAME = " + DB_NAME + "_Data, "
+ " FILENAME = '" + DB_PATH + DB_NAME + ".mdf', "
+ " SIZE = 2MB,"
+ " FILEGROWTH = 10%) "
+ " LOG ON (NAME =" + DB_NAME + "_Log, "
+ " FILENAME = '" + DB_PATH + DB_NAME + "Log.ldf', "
+ " SIZE = 1MB, "
+ " FILEGROWTH = 10%) ";
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception)
{
stat=false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
myConn.Dispose();
}
return stat;
}
关于c# - 创建和连接到 SQL Server 数据库的代码 : Whats wrong with it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9321206/