日期:2014-05-18  浏览次数:20662 次

求教,为啥使用如下代码插入ACCESS数据库的时候一下插入n多
如题,代码如下,运行的时候插入数据未响应,半天后发现插入了数十次,求大侠帮忙看看问题出在哪里....小弟感激不尽...
string ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\db1.mdb";
  OleDbConnection conn = new OleDbConnection();
  String str = "./db1.mdb";
  OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.jet.OLEDB.4.0;Data Source=" + str + ";User ID=admin;Password=;Jet OLEDB:Database Password=");
  try
  {
  OleDbcon.Open();
  OleDbCommand cmd = new OleDbCommand("insert into "+comboBox1.Text.ToString()+" (商品名称,单位,售价,进价) values(@textBox2,@textBox3,@textBox4,@textBox5)", OleDbcon);
  cmd.Parameters.AddWithValue("@textBox2", textBox2.Text.Trim());
  cmd.Parameters.AddWithValue("@textBox3", textBox3.Text.Trim());
  cmd.Parameters.AddWithValue("@textBox4", textBox4.Text.Trim());
  cmd.Parameters.AddWithValue("@textBox5", textBox5.Text.Trim());
  int result = cmd.ExecuteNonQuery();
  if (result > 0)
  {
  button6_Click(null, null);
  textBox2.Text = string.Empty;
  textBox3.Text = string.Empty;
  textBox4.Text = string.Empty;
  textBox5.Text = string.Empty;
  }
  else
  MessageBox.Show("添加失败!");
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  finally
  {
  OleDbcon.Close();
  }

------解决方案--------------------
你这段代码写在哪了,是不是被循环触发了,跟踪一下看看吧
------解决方案--------------------
探讨

就是一个按钮的点击事件,检测所填的textbox是否为空,为空则提示,不为空则执行添加,代码如下:
private void button6_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox2.Text.Trim()))
{
……