【发布时间】:2013-05-03 13:55:33
【问题描述】:
我一直是“如果它没有坏就不要修复它”的粉丝
但是我的代码虽然可以正常运行,但会抛出 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
}
【问题讨论】:
-
someconnectionstring.Value的值是多少? -
你能解释一下“抛出异常但继续工作”的意思吗?当然,如果抛出异常,您的 SqlDataReader 代码将被完全跳过,因此它不起作用?是间歇性故障吗?
-
sconn.ToString()永远不会是null或为空。也许sconn.ConnectionString,取决于someconnectionstring.Value.ToString()是什么。
标签: c# code-behind sqlconnection