我有一个有趣的时间使用下面的声明,如下所示
SqlCommand RiskRevalCommand =
new SqlCommand("select * from CreditAdmin.dbo.CreditData_Test");
我直接从SQL Server Management Studio中的查询中获取了SQL语句,因此我知道它在那里工作,但现在它会在程序尝试执行此行时引发异常:
SqlDataReader reader = RiskRevalCommand.ExecuteReader();
,错误如下:
ExecuteReader:尚未初始化Connection属性。
SqlConnection xavierConnection =
new SqlConnection("user id=FB\\user;" +
"password=password;" +
"server=dataserver;" +
"Trusted_Connection=yes;" +
"database=CreditAdmin;" +
"connection timeout=15");
try
{
xavierConnection.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
try
{
SqlCommand RiskRevalCommand = new SqlCommand("select * from CreditAdmin.dbo.CreditData_Test");
SqlDataReader reader = RiskRevalCommand.ExecuteReader();
while (reader.Read())
{
try
{
double.TryParse(reader["Available Balance"].ToString(), out _availability);
...
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
//close the connection
try
{
xavierConnection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
我应该对我的SQL语句进行哪些更改,以便它不会爆炸,以便我仍然可以为字段执行TryParsing?
当this有效时,这又如何破解?
(这就是我现在使用的select *
所在的位置)
答案 0 :(得分:3)
请记住在SqlCommand构造函数中添加SqlConnection。
http://msdn.microsoft.com/en-us/library/877h0y3a.aspx
像:
var cmd = new SqlCommand(thisSelectStatementString, myConnection);
或者柯克提到:
var cmd = myConnection.CreateCommand(thisSelectStatementString);
答案 1 :(得分:0)
我认为你的连接在上面的try范围中被阻止了,试试这个
try
{
xavierConnection.Open();
SqlCommand RiskRevalCommand = new SqlCommand("select * from CreditAdmin.dbo.CreditData_Test", xavierConnection/*don't forget this*/);
SqlDataReader reader = RiskRevalCommand.ExecuteReader();
while (reader.Read())
{
//no need to try-catch here
double.TryParse(reader["Available Balance"].ToString(), out _availability);
...
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
xavierConnection.Close();
}
并且您也设置了Trusted_Connection=true
,但您已设置username
并且password
将其更改为false,
在连接字符串中尝试此格式
ConnectionString = "server=Server; user id=FB\\user; password=top$secret;" +
"database=dataserver; Trusted_Connection=false; Asynchronous Processing=true";