2

我一直是“如果它没有坏就不要修复它”的粉丝,但我的代码虽然可以正常运行,但会抛出connectionstring 属性尚未初始化消息。类似的帖子表明连接字符串为空---所以我if IsNullOrEmpty在连接打开命令周围添加了一个。这是引发异常的行。注意:我的连接字符串是从连接字符串数据库中检索的。这是 .aspx 页面的 c# 代码隐藏文件。预先感谢您对异常原因的任何建议。

编码:

using (SqlConnection sconn = new SqlConnection(someconnectionstring.Value.ToString()))
        {
            using (SqlCommand scmd = new SqlCommand("mydb.[dbo].[myStoredProc]", sconn))
            {
                scmd.CommandType = CommandType.StoredProcedure;
                scmd.Parameters.Add("@valueX", SqlDbType.VarChar).Value = 2; 
                scmd.Parameters.Add("@returnValue", SqlDbType.Int);
                scmd.Parameters["@returnValue"].Direction = ParameterDirection.Output;
        //testing for null as suggested...
        if (!string.IsNullOrEmpty(sconn.ToString()) || sconn.ToString() != "")   //the ||  != "" may be double work.. not sure
                {
                    sconn.Open();  //code throw exception here but continues to work.
                    SqlDataReader adar = scmd.ExecuteReader();
                    if (adar.HasRows)
                    {

                        while (adar.Read())
                        {
                            hiddenfieldX.Value = adar["valueX"].ToString();
            ...
                        }
                        sconn.Close();
                    }
                }
            }
        }
    }
    catch (SqlException er)
    {
    //The ConnectionString property has not been initialized thrown here
    } 
4

1 回答 1

1

正如队友所说,连接字符串可能为空或格式不正确。

1-检查您的连接字符串是否正确(您可以发布它,我们可以检查)

2-如果它看起来像这样,您的代码会更好:

string someconnectionstring = "yourConnectionString";

if (!string.IsNullOrEmpty(someconnectionstring))
{
    using (SqlConnection sconn = new SqlConnection(someconnectionstring))
    {
        using (SqlCommand scmd = new SqlCommand("mydb.[dbo].[myStoredProc]", sconn))
        {
            scmd.CommandType = CommandType.StoredProcedure;
            scmd.Parameters.Add("@valueX", SqlDbType.VarChar).Value = 2;
            scmd.Parameters.Add("@returnValue", SqlDbType.Int);
            scmd.Parameters["@returnValue"].Direction = ParameterDirection.Output;

            sconn.Open();  //code throw exception here but continues to work.
            SqlDataReader adar = scmd.ExecuteReader();
            if (adar.HasRows)
            {

                while (adar.Read())
                {
                    //...
                }
            }                
            sconn.Close();
        }
    }
}
于 2013-05-03T05:55:33.650 回答