2012-04-03 67 views
1

我想要的應用程序在WPF與數據庫連接,當我選擇數據庫我要顯示這樣的信息:小問題連接到SQL Server 2008與C#2010

[文件名]密度纖維板目前正在使用中。寫一個新名字或關閉正在使用該文件的其他程序。

問題是,當時我沒有任何其他使用數據庫的程序。

誰能告訴我爲什麼會發生這種情況?提前致謝。

+0

我認爲這是一個SqlCE數據庫?也許Visual Studio保持與數據庫的連接,這就是爲什麼你會得到錯誤? – joshuahealy 2012-04-03 02:13:54

回答

5

如何祈禱,你是否連接到數據庫? 請勿直接打開文件。您需要連接到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

+0

謝謝!那訣竅:) – 2012-04-07 05:19:38