2014-10-19 79 views
0

我創建了一個本地SQL Server數據庫和登錄形式,這裏是登錄窗體的代碼:C#無法連接到本地SQL數據庫

namespace WindowsFormsApplication1 
{ 
    public partial class LoginForm : Form 
    { 
     public LoginForm() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      if (!(Usertxt.Text == string.Empty)) 
      { 
        SqlConnection connection = new SqlConnection(@"Data Source=|DataDirectory|\crimemanagement.sdf"); 
        connection.Open(); 

        SqlCommand cmd = new SqlCommand(@"SELECT Count(*) FROM Login_table 
             WHERE [email protected] and 
             [email protected]", connection); 

        cmd.Parameters.AddWithValue("@Username", Usertxt.Text); 
        cmd.Parameters.AddWithValue("@Password", Passtxt.Text); 

        int result = (int)cmd.ExecuteScalar(); 

        if (result > 0) 
        { 
         MessageBox.Show("Login Success"); 
        } 
        else 
        { 
         MessageBox.Show("Incorrect login"); 
        } 
      } 
      else if (Passtxt.Text == string.Empty || Usertxt.Text == string.Empty) 
      { 
       MessageBox.Show("Enter Username and Password"); 
      } 
     } 
    } 
} 

但是當我嘗試使用我創建的表單進行登錄它給我一個連接錯誤,並強調connection.open();

System.Data.SqlClient.SqlException was unhandled

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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

+1

你應該使用'using'塊。並且請不要將明文密碼放入數據庫。 – nvoigt 2014-10-19 15:49:28

回答

2

爲了在ADO.NET與SQL Server Compact數據庫文件工作,你需要使用System.Data.SqlServerCe.dll ADO.NET提供者,並使用對象像SqlCeConnection,SqlCeCommand等。

+0

謝謝,會試試....... – aliadiere 2014-10-19 15:55:45

+0

工作過,非常感謝... – aliadiere 2014-10-19 16:07:08

0

您使用SqlConnection這是正確 SQL服務器(基於服務器的系統),但你引用一個的SQL Server CE數據文件(.sdf)。

如果你想使用.sdf,則需要使用SqlCeConnectionSqlCeCommand等 - SqlConnectionSqlCommand

+0

謝謝,會試試....... – aliadiere 2014-10-19 15:53:52

+0

我不行.......:/ – aliadiere 2014-10-19 15:57:41

+0

Got它,工作謝謝..... – aliadiere 2014-10-19 16:19:01