为什么我不能通过 c# windows 形式的 sql 查询将数值插入到 MS Access 数据库中?

问题描述

我使用以下代码数据库中插入数据

public partial class Products : Form
{
    private OleDbConnection connection = new OleDbConnection();
    public Products()
    {
        InitializeComponent();
        connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Folder\Database.mdb;Persist Security Info=False;";
    }
private void cmdAdd_Click(object sender,EventArgs e)
    {
        try
        {
            connection.open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "INSERT INTO Products (ProductName,Quantity,Weight(g)) VALUES ('" + txtName.Text + "','" + txtQuantity.Text + "','" + txtWeight.Text + "')";
            
            command.ExecuteNonQuery();
            MessageBox.Show("Data saved");
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
        

    }

最后两个变量似乎不起作用。我尝试为第一个字段输入一个字符串,它运行良好,但是当我在最后两个变量上插入一个数字时,它会引发异常。我已经尝试过做 int.Parse(txtQuantity.Text) 但它也不起作用。

解决方法

通过从最后 2 个项目中删除 ' 来更改您的字符串:


command.CommandText = "INSERT INTO Products (ProductName,Quantity,Weight(g)) 
VALUES ('" + txtName.Text + "'," + txtQuantity.Text + "," + txtWeight.Text + ")";