出现如下绿色字体出错的问题,是由于using使用过后数据库会自动关闭,出了using的作用域后,在调用的时候无法找到信息
form1.cs
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] parameters)
{
string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteReader();
}
}
}
DBHelper.cs
private void button2_Click(object sender, EventArgs e)
{
SqlDataReader reader = DBHelper.ExecuteReader("select * from T_Person");
while (reader.Read ())
{
string name = reader.GetString(reader.GetOrdinal("Name"));
MessageBox.Show(name);
}
}
改:将Using去掉,用手动打开open、关闭close,用cmd.ExecuteReader(CommandBehavior.CloseConnection)
form1.cs
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] parameters)
{
string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
DBHelper.cs
private void button2_Click(object sender, EventArgs e)
{
SqlDataReader reader = DBHelper.ExecuteReader("select * from T_Person");
while (reader.Read ())
{
string name = reader.GetString(reader.GetOrdinal("Name"));
MessageBox.Show(name);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/36476.html