【问题标题】:Access database insert is not succesfulAccess数据库插入不成功
【发布时间】:2019-11-15 14:06:09
【问题描述】:

我正在尝试将一些数据从我的文本框中插入到 MS Access 数据库中。

代码运行成功,但新数据没有出现在数据库中。

所有数据类型或短文本

try
{
    OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dsms.accdb");
    connection.Open();
      string Dcode = textDcode.Text;
      string Dname = textDname.Text;
      string Units = textDunit.Text;
      string Price = textDbuyp.Text;
      string BPrice = textDsellp.Text;
      string Category = textDcategory.Text;

      string my_query = "INSERT INTO Drugs(Dcode, Dname, Units, Price, BPrice, Category)VALUES('"+Dcode+"','"+Dname+"','"+Units+"','"+Price+"','"+BPrice+"','"+Category+"')";

      OleDbCommand cmd = new OleDbCommand(my_query, connection);
      cmd.ExecuteNonQuery();

      MessageBox.Show("Data saved successfully");
  }
  catch (Exception ex)
  {
      MessageBox.Show("Failed due to " + ex.Message);
  }
  finally
  {
      connection.Close();
  }

【问题讨论】:

  • 没有错误?你确定吗?这些变量中是否有单引号?
  • 您容易受到 SQL 注入 的攻击。此外,你怎么知道没有插入数据?你在检查正确的数据库/表吗?
  • @JNevill:公平地说,INSERT 不会抛出很多异常。他至少确实暴露了这个信息。所以这不是异常处理的全部罪过。
  • @JNevill 是的,我什至确定没有异常错误
  • @Rahul SQL 注入现在无关紧要。我确实检查了记录

标签: c# sql ms-access


【解决方案1】:

1) 使用实数值创建插入语句。 为此,在字段中放置一个中断点

  string Dcode = textDcode.Text;
  string Dname = textDname.Text;
  string Units = textDunit.Text;
  string Price = textDbuyp.Text;
  string BPrice = textDsellp.Text;
  string Category = textDcategory.Text;

例子:

INSERT INTO Drugs(Dcode, Dname, Units, Price, BPrice, Category)VALUES('0001','nombre A','3','3454545','2453245','categoria A')

并使用这些值手动构建您的句子。在您的数据库引擎中单独运行它。

2) 确认您从数据库控制台正确插入到表中。

3) 正确插入句子后,从 c# 代码中设置并尝试从 c# 插入。 示例:

 string my_query = "INSERT INTO Drugs(Dcode, Dname, Units, Price, BPrice, Category)VALUES('0001','nombre A','3','3454545','2453245','categoria A')";

4) 当c#中的insert起作用时,将字段的值替换为变量。 示例:

 string my_query = String.Format("INSERT INTO Drugs(Dcode, Dname, Units, Price, BPrice, Category)VALUES('{0}','{1}','{2}','{3}','{4}','{5}')",Dname, Units, Price, BPrice, Category) ;

【讨论】:

    【解决方案2】:

    尝试断开并连接您的 Microsoft Access 数据库,然后再次检查数据

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      相关资源
      最近更新 更多