2011-08-24 85 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是对的@ –