在MS Access DB中插入函数
本文关键字:插入 函数 DB MS Access | 更新日期: 2023-09-27 17:52:57
我是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();
}
}
首先,我注意到这一行:
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。下面是我编写的一个示例,用于演示如何为UPDATE
语句使用参数化SQL。该代码主要适用于其他语句类型,如SELECT
或INSERT
。
尽管,实际上,您应该评估使用JET/ACE进行数据访问。JET是Windows自带的,但ACE不是。在你的代码中,你依赖于ACE。请考虑是否依赖于SQL Server LocalDB会更好。
将查询替换为:
string ab = string。Format("insert into Hello values({0}, '{1}')", int。解析(textBox1。文本),textBox2。文本);