我正在尝试将 WPF 中的应用程序与数据库连接,当我选择数据库时,我希望显示此消息:
[filename].mdf is currently in use. Write a new name or close the other program that's using the file.
问题是当时我没有任何其他程序使用数据库。
谁能告诉我为什么会这样?提前致谢。
最佳答案
请问,您是如何连接到数据库的? 不要直接打开文件。您需要连接到 SQL Server。
您需要一个连接字符串,典型的连接字符串如下所示:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
代码应该是这样的:
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
// 2. Open the connection
conn.Open();
// 3. Pass the connection to a command object
SqlCommand cmd = new SqlCommand("select * from Customers", conn);
//
// 4. Use the connection
//
// get query results
rdr = cmd.ExecuteReader();
// print the CustomerID of each record
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
}
示例来自:http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson02.aspx
关于c# - 使用 C# 2010 连接到 SQL Server 2008 的小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9986236/