我想将数据从ListView
保存到MySQL数据库。项SubTotal
,Cash
和Kembalian
应保存到MySql的表中:
int SubTotal = 0;
int Cash = 0;
int Kembalian = 0;
for (int i = 0; i < ListView1.Items.Count; i++)
{
SubTotal = Convert.ToInt32(ListView1.Items[i].SubItems[4].Text);
Cash = Convert.ToInt32(ListView1.Items[i].SubItems[4].Text);
Kembalian = Convert.ToInt32(ListView1.Items[i].SubItems[4].Text);
string constring = "datasource=localhost;port=3306;username=root;password=elga";
string Query = "insert into cimonedb.penjualan (SubTotal, Cash, Kembalian) values('" + SubTotal + "','" + Cash + "','" + Kembalian + "',)";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Transsaksi is Seved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:1)
你有这个问题:
,
声明末尾有一个额外的逗号insert
。cmdDataBase.ExecuteNonQuery();
代替cmdDataBase.ExecuteReader();
并删除while (myReader.Read()) { }
conDataBase.Close();
最好使用Using statement
提供一种更简单的方法来指定何时需要非托管资源。
虽然您的代码不容易受SQL Injection
攻击,但强烈建议您始终使用parameterized queries
。