2011-08-24 76 views
2

當我嘗試使用ADO.NET建立與SQL Server的連接時,它顯示錯誤。ADO.NET連接結果實例失敗

這是我的代碼使用方法:

SqlConnection con = new SqlConnection(@"Data Source=.\\SQLEXPRESS;Initial Catalog=abdul;uid=sa;pwd=sqlserver"); 
SqlCommand cmd = new SqlCommand(); 

con.Open(); 

String str="select * from emp where empname='Abdul'"; 
cmd = new SqlCommand(str, con); 

SqlDataReader dr = cmd.ExecuteReader(); 

if (dr == null || !dr.HasRows) 
{ 
    MessageBox.Show("No Records found"); 
} 
else 
{ 
    while (dr.Read()) 
    { 
     textBox1.Text = dr[0].ToString(); 
     textBox2.Text = dr[1].ToString(); 
    } 
} 

當我運行項目它顯示了以下錯誤:

Instance failure.

我有什麼做的?

+2

您可以複製錯誤堆棧跟蹤嗎? –

+0

@Alberto Leon:以下是系統上System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,SqlInternalConnectionTds connHandler,Boolean ignoreSniOpenTimeout,Int64 timerExpire,布爾加密,Boolean trustServerCert,布爾integratedSecurity,SqlConnection擁有對象)的錯誤堆棧跟蹤 。 Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo,String newPassword,Boolean ignoreSniOpenTimeout,Int64 timerExpire,SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String這是不夠的,把所有 –

+0

爲什麼你不使用ConnectionStringBuilder for this:SqlConnection(@「Data Source =。\\ SQLEXPRESS; Initial Catalog = abdul; uid = sa; pwd = sqlserver」);? –

回答

11

如果您標記使用@連接字符串,使其文字,你應該只使用一個反斜槓在數據源

DataSource=.\SQLEXPRESS

+0

我也試過,當我嘗試這個時,它顯示以下錯誤:用戶'sa'登錄失敗。用戶未與可信的SQL Server連接相關聯。 –

+0

非常感謝,真正的問題是連接字符串,我糾正了通過使用DataSource。真的很感謝你... –

+0

你的問題只是憑證,@PaulB是對的@ –