使用datagridView,INSERT命令发生异常,而删除和更新在使用access数据库的C#中运行良好

本文关键字:数据库 access 运行 更新 命令 INSERT datagridView 异常 删除 使用 | 更新日期: 2023-09-27 18:27:47

使用我表单中的保存按钮,除了INSERT命令外,所有操作(更新、删除)都能正常工作。帮我摆脱困境。。。

public partial class frmeditaccess : Form
{
    string table = "master";
    OleDbDataAdapter da;
    OleDbCommandBuilder cb;
    DataTable dt;
    OleDbConnection conn;
    string query;
    public frmeditaccess()
    {
        InitializeComponent();
    }
    private void btload_Click(object sender, EventArgs e)
    {
        try
        {
            conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source= C:'Users'ViPuL'Documents'Visual Studio 2010'Projects'feedback@MERI'feedback@MERI'bin'feedback.mdb";
            query = string.Format("SELECT * FROM {0}", table);
            da = new OleDbDataAdapter(query, conn);
            dt = new DataTable();
            dataGridView1.DataSource = dt;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed due to " + ex.Message);
        }
    }
    private void btsave_Click(object sender, EventArgs e)
    {
        try
        {
            cb = new OleDbCommandBuilder(da);
            da.Update(dt);      //here update, delete are working. Only, Insert throws exception of syntax error in INSERT command.
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed due to " + ex.Message);
        }
    }     

使用datagridView,INSERT命令发生异常,而删除和更新在使用access数据库的C#中运行良好

这可能是由于保留关键字用作列名,请尝试在下面指定QuotePrefix和QuoteSuffix

cb = new OleDbCommandBuilder(da);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
da.Update(dt);