private void button1_Click(object sender, EventArgs e)
{
int f = 1;
SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
int bal = 0;
string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
cmd.CommandText = cmdstr;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
bal = int.Parse(dr[2].ToString());
int draw = int.Parse(textBox1.Text);
if(draw > bal)
{
MessageBox.Show("Insufficient balance!");
return;
}
else
{
bal -= draw;
cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = cmdstr;
try
{
da.UpdateCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
f = 0;
}
if (f == 1)
MessageBox.Show("Money withdrawn succesfully!");
else
MessageBox.Show("Enter correct amount!");
}
con.Close();
}
执行此程序时出现“InvalidOperationException”。我不确定错误是什么。请帮忙。
da.UpdateCommand.ExecuteNonQuery()
未执行
答案 0 :(得分:0)
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....
try
{
sqlcmd.ExecuteNonQuery();
....
请勿使用适配器。
是的。更快的尝试关闭连接并打开新的更新操作。