0

我是 C# 新手,我的项目需要帮助。请协助!

我想创建一个插入函数,允许我将数据插入到我的 MS Access DB 中。但是,我不断收到错误消息,指出语句末尾缺少分号 (;) 并且数据不会结束

下面是我的代码,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Insert
{
    public partial class Form1 : Form
    {

    OleDbConnection vcon= new  OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C://Database//HelloDB.accdb");
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        vcon.Open();

    }

    private void buttonExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void buttonSave_Click(object sender, EventArgs e)
    {
        string ab = string.Format("insert into Hello values(id, 'Hname'))", int.Parse(textBox1.Text), textBox2.Text);
        OleDbCommand vcom = new OleDbCommand(ab, vcon);
        vcom.ExecuteNonQuery();
        MessageBox.Show("Data stored successfully");
        vcom.Dispose();
    }

}
4

2 回答 2

1

首先,这条线在我身上很突出:

string ab = string.Format("insert into Hello values(id, 'Hname'))", int.Parse(textBox1.Text), textBox2.Text);

我相信它应该是:

                                                            /*!*/
string ab = string.Format("insert into Hello values({0}, '{1}')", int.Parse(textBox1.Text), textBox2.Text);

其次,您应该为此使用参数化 SQL。是我编写的一个示例,用于演示如何将参数化 SQL 用于UPDATE语句。该代码主要适用于其他语句类型,例如SELECTor INSERT

虽然,实际上,您应该评估您使用 JET/ACE 进行数据访问的情况。JET 带有 Windows,但 ACE 没有。因此,在您的代码中,您依赖于 ACE。考虑是否更好地依赖 SQL Server LocalDB。

于 2013-01-12T05:29:56.593 回答
0

将您的查询替换为以下内容:

string ab = string.Format("插入 Hello 值({0}, '{1}')", int.Parse( textBox1.Text ), textBox2.Text );

于 2013-01-12T05:56:47.480 回答