黑马程序员技术交流社区
标题:
DataReader没有关闭的问题
[打印本页]
作者:
lx19921105
时间:
2014-3-28 19:26
标题:
DataReader没有关闭的问题
C# +SqlServer2008 做的一个系统.老是提示 ( 已有打开的与此命令想关联的DataReader,必须首先将它关闭) 我试着在不同地方加reader.close()还是不行. 但是以前我用C#+Oracle做的时候就没这个问题. cmd.ExecuteNonQuery();出错的这局
int x, nx,zx;
string sss;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=(local);database=mystudent1;integrated security=SSPI ";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("select balance from cards111 where id='{0}'", uid);
SqlDataReader reader;
reader = cmd.ExecuteReader();
if (reader.Read())
{
x = Convert.ToInt32(reader["balance"].ToString());
zx = Convert.ToInt32(textBox1.Text);
nx = x + zx;
sss=nx.ToString();
cmd.CommandText = string.Format("update cards111 set balance='{0}' where id='{1}'", sss, uid);
object obj1 =
cmd.ExecuteNonQuery();
if (obj1 == null)
{
MessageBox.Show("error");
}
else
{
cmd.CommandText = string.Format("insert into records111 values('{0}','{1}','{2}',to_date('{3}','yyyy-mm-dd hh24:mi:ss'))", uid, "存款", zx, DateTime.Now.ToString());
object obj = cmd.ExecuteNonQuery();
if (obj == null)
{
MessageBox.Show("error2");
}
else
{
MessageBox.Show("存款成功");
cmd.CommandText = string.Format("commit");
textBox1.Clear();
}
}
}
else
{
MessageBox.Show("error");
}
reader.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
conn.Dispose();
cmd.Dispose();
}
作者:
白夜行
时间:
2014-3-29 10:08
你用using试试,我把你代码改了一下,没调试
string dbStr = "server=(local);database=mystudent1;integrated security=SSPI ";
using (SqlConnection conn = new SqlConnection(dbStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = string.Format("select balance from cards111 where id='{0}'", uid);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
x = Convert.ToInt32(reader["balance"].ToString());
zx = Convert.ToInt32(textBox1.Text);
nx = x + zx;
sss = nx.ToString();
cmd.CommandText = string.Format("update cards111 set balance='{0}' where id='{1}'", sss, uid);
object obj1 = cmd.ExecuteNonQuery();
if (obj1 == null)
{
MessageBox.Show("error");
}
else
{
cmd.CommandText = string.Format("insert into records111 values('{0}','{1}','{2}',to_date('{3}','yyyy-mm-dd hh24:mi:ss'))", uid, "存款", zx, DateTime.Now.ToString());
object obj = cmd.ExecuteNonQuery();
if (obj == null)
{
MessageBox.Show("error2");
}
else
{
MessageBox.Show("存款成功");
cmd.CommandText = string.Format("commit");
textBox1.Clear();
}
}
}
else
{
MessageBox.Show("error");
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2