将数据从Listview保存到MySQL

时间:2015-10-15 16:17:23

标签: c# mysql

我想将数据从ListView保存到MySQL数据库。项SubTotalCashKembalian应保存到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);
      }
}

1 个答案:

答案 0 :(得分:1)

你有这个问题:

  1. ,声明末尾有一个额外的逗号insert
  2. 您应该使用cmdDataBase.ExecuteNonQuery();代替cmdDataBase.ExecuteReader();并删除while (myReader.Read()) { }
  3. 您错过了conDataBase.Close();
  4. 最好使用Using statement提供一种更简单的方法来指定何时需要非托管资源。

    虽然您的代码不容易受SQL Injection攻击,但强烈建议您始终使用parameterized queries