try
{
sqlCommandWithdraw.Connection.Open();
sqlCommandWithdraw.Parameters["@cardNumber"].Value = Class1.cardNumber;
readdata = sqlCommandWithdraw.ExecuteReader();
while (readdata.Read())
{
balanceDB = decimal.Parse(readdata["balance"].ToString());
}
decimal withdrawAmm = Convert.ToDecimal(textWithdraw.Text);
balanceDB = balanceDB - withdrawAmm;
sqlCommandWithdraw.Connection.Close();
sqlCommandUpdate.Connection.Open();
sqlCommandUpdate.Parameters["@cardNumber"].Value = Class1.cardNumber;
sqlCommandUpdate.Parameters["@balanceDB"].Value = Class1.cardNumber;
readdata = sqlCommandUpdate.ExecuteReader();
MessageBox.Show(balanceDB +" Successfully Withdrawn");
}
我正在为ATM机编写代码,我在提款上有些东西,看起来不错,但似乎并没有改变余额以反映数据库中的提款
我的命令是这样的(更新)
update dbo.Accounts
set balance = @balanceDB
from dbo.ATMCards
INNER JOIN dbo.Accounts ON dbo.ATMCards.accountID = dbo.Accounts.accountID
where (dbo.ATMCards.cardNumber = @cardNumber)
这是我选择数据的命令
select dbo.Accounts.balance
from dbo.ATMCards
INNER JOIN dbo.Accounts ON dbo.ATMCards.accountID = dbo.Accounts.accountID
where (dbo.ATMCards.cardNumber = @cardNumber)
似乎运行得很好,添加了消息框以进行检查,感谢您的帮助!
最佳答案
您正在将信用卡号传递给参数@balanceDB
-这是第一个错误。其次,您不使用ExecuteReader
执行更新-而是使用ExecuteNonQuery
。
编辑
我会为您做一些清理工作:
try
{
try
{
sqlCommandWithdraw.Connection.Open();
sqlCommandWithdraw.Parameters["@cardNumber"].Value = Class1.cardNumber;
// Make sure to dispose of the reader, which also closes the reader, which
// is important, because you can't perform any other selects on a connection
// with an open reader!
using (SqlDataReader reader = sqlCommandWithdraw.ExecuteReader())
{
// You will only get one line - also, your code also only evaluates
// one result, so we can do the following:
if (reader.Read())
{
balanceDB = decimal.Parse(readdata["balance"].ToString());
}
}
}
finally
{
sqlCommandWithdraw.Connection.Close();
}
decimal withdrawAmm = Convert.ToDecimal(textWithdraw.Text);
balanceDB = balanceDB - withdrawAmm;
try
{
sqlCommandUpdate.Connection.Open();
sqlCommandUpdate.Parameters["@cardNumber"].Value = Class1.cardNumber;
sqlCommandUpdate.Parameters["@balanceDB"].Value = balanceDB;
sqlCommandUpdate.ExecuteNonQuery();
MessageBox.Show(balanceDB +" Successfully Withdrawn");
}
finally
{
sqlCommandUpdate.Connection.Close();
}
}