0

我正在使用下面这样的声明度过一段有趣的时光

SqlCommand RiskRevalCommand = 
    new SqlCommand("select * from CreditAdmin.dbo.CreditData_Test");

我直接从 SQL Server Management Studio 中的查询中获取了 SQL 语句,所以我知道它在那里工作,但现在当程序尝试执行此行时,它会导致抛出异常:

SqlDataReader reader = RiskRevalCommand.ExecuteReader();

错误内容如下:

ExecuteReader:连接属性尚未初始化。

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?

另外,当它起作用时,这到底是怎么破的?

(这就是select *我现在使用的地方)

4

2 回答 2

3

请记住在 SqlCommand 构造函数中添加 SqlConnection。

http://msdn.microsoft.com/en-us/library/877h0y3a.aspx

喜欢:

var cmd = new SqlCommand(thisSelectStatementString, myConnection);

或者正如柯克所说:

var cmd = myConnection.CreateCommand(thisSelectStatementString);
于 2013-04-12T01:14:56.893 回答
0

我认为您的连接在上面的尝试范围内被阻止,试试这个

        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但您已经设置了 ausername并将其password更改为 false,

在您的连接字符串中尝试这种格式

ConnectionString = "server=Server; user id=FB\\user; password=top$secret;" +
            "database=dataserver; Trusted_Connection=false; Asynchronous Processing=true";
于 2013-04-12T00:38:51.730 回答