我正在學習 C#,作為 .Net 練習的一部分,我需要為用戶提供一個表單,其中包含 from、to 和 amount 欄位以及當用戶點擊傳輸按鈕時。應用程式應從 from account_id 中扣除金額并將錢添加到 To account_id
這是我的按鈕功能代碼
string mysql_conn_string = "server=localhost;user=root;database=vsp;port=3306;password=password";
MySqlConnection con = new MySqlConnection(mysql_conn_string);
con.Open();
string s1 = "update bank set amount = amount - " textBox3.Text "where account_id = " textBox1.Text;
string s2 = "update bank set amount = amount " textBox3.Text "where account_id = " textBox2.Text;
MySqlTransaction tx = con.BeginTransaction();
MySqlCommand cmd = new MySqlCommand(s1, con, tx);
int a = cmd.ExecuteNonQuery();
MySqlCommand cmd2 = new MySqlCommand(s2, con, tx);
int b = cmd2.ExecuteNonQuery();
if (a == 0 || b == 0)
{
tx.Rollback();
MessageBox.Show("Rolling bacck");
}
else
{
tx.Commit();
MessageBox.Show("Transaction Succesful");
}
con.Close();
我收到以下錯誤:您的 SQL 語法有錯誤;檢查與您的 MySqlserver 版本相對應的手冊,了解在第 1 行的“account_id = 2”附近使用的正確語法
但是相同的 sql 陳述句在 mysql 作業臺中正常作業并且沒有顯示任何錯誤。
我的表有 account_id 和 amount 列。
兩個都是INT
我嘗試使用 Int32.Parse 和 Int64.Parse 將文本框型別更改為 INT
uj5u.com熱心網友回復:
您的代碼中有許多嚴重的問題
- 您的主要問題:由于缺少空格而導致語法錯誤。
- 如果您正確地引數化您的查詢,您會更快地發現這一點,以避免 SQL 注入。
- 您需要
Sql使用 a處理所有物件using(然后您不需要Close顯式呼叫)。 - 您可以一次執行這兩個陳述句。
- 如果它不起作用,則無需有條件地回滾。而是檢查行是否存在。
- 您不應該對連接字串進行硬編碼,而是將其放入設定檔案中。
- 不要在連接打開時用訊息框阻塞執行緒。
using (var con = new MySqlConnection(Properties.Settings.ConnectionString))
{
const string query = @"
start transaction;
if (select count(*)
from bank
where account_id in (@s1, @s2)
) = 2 then
update bank
set amount = amount (case when account_id = @s1 then -@amt else @amt end)
where account_id in (@s1, @s2);
end if;
commit;
";
using (var cmd = new MySqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@s1", textBox1.Text);
cmd.Parameters.AddWithValue("@s2", textBox2.Text);
cmd.Parameters.AddWithValue("@amt", textBox3.Text);
con.Open();
rows = cmd.ExecuteNonQuery();
}
}
if (rows == 0)
{
MessageBox.Show("Not executed");
}
else
{
MessageBox.Show("Transaction Succesful");
}
uj5u.com熱心網友回復:
從我所看到的,錯誤不在 WHERE 條件上,而是在資料上,因為您需要添加一個空格。你有這個:
string s1 = "update bank set amount = amount - " textBox3.Text "where account_id = " textBox1.Text;
string s2 = "update bank set amount = amount " textBox3.Text "where account_id = " textBox2.Text;
然后,當構建查詢時,您將擁有:
s1 = "update bank set amount = amount - 100where account_id = 1";
如您所見,WHERE 和 textBox3 上的文本放在一起,嘗試添加一個空格,如下所示:
string s1 = "update bank set amount = amount - " textBox3.Text " where account_id = " textBox1.Text;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403423.html
標籤:
上一篇:如何呼叫泛型方法
