ConnectionString属性尚未初始化,但代码仍然可以工作

本文关键字:工作 代码 属性 初始化 ConnectionString | 更新日期: 2023-09-27 18:12:01

我一直是"如果没坏就不要修"的粉丝。但是我的代码,虽然功能,是抛出 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
    } 

ConnectionString属性尚未初始化,但代码仍然可以工作

如上所述,连接字符串可能为空或格式不正确。

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();
        }
    }
}