我一直是“如果它没有被破坏而不修复它”的粉丝
但我的代码,虽然正常运行,但是抛出 connectionstring属性还没有初始化消息。类似的帖子暗示连接字符串为null ---所以我在连接打开命令周围添加了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
}
答案 0 :(得分: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();
}
}
}