[英]Insert function to MS Access DB
Am new to C# and need help for my project. 我是C#的新手,需要我的项目的帮助。 Please assist! 请协助!
I want to create a insert function which allows me to insert data into my MS Access DB. 我想创建一个插入函数,使我可以将数据插入MS Access DB。 However, i keep getting a error stating that missing semicolon (;) at the end of statement and the data won't be ended 但是,我不断收到错误消息,指出语句末尾缺少分号(;),并且数据不会结束
Below is my code, 下面是我的代码,
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();
}
}
First, this line sticks out at me: 首先,这条线向我伸出来:
string ab = string.Format("insert into Hello values(id, 'Hname'))", int.Parse(textBox1.Text), textBox2.Text);
I believe it should read: 我相信它应该显示为:
/*!*/
string ab = string.Format("insert into Hello values({0}, '{1}')", int.Parse(textBox1.Text), textBox2.Text);
Second, you should use parameterised SQL for this. 其次,您应该为此使用参数化的SQL。 Here is an example I wrote to demonstrate how to use parameterised SQL for UPDATE
statements. 这是我编写的示例,以演示如何对UPDATE
语句使用参数化SQL。 The code is mostly applicable to other statement types, like SELECT
or INSERT
. 该代码主要适用于其他语句类型,例如SELECT
或INSERT
。
Although, really, you should evaluate your use of JET/ACE for data access. 虽然,实际上,您应该评估对数据访问的使用JET / ACE。 JET comes with Windows, but ACE does not. JET随Windows一起提供,但ACE不提供。 So in your code you have a dependency on ACE. 因此,在您的代码中,您对ACE有依赖性。 Consider if it would be better to have a dependency on SQL Server LocalDB, instead. 考虑一下,最好还是依赖于SQL Server LocalDB。
Replace your query with following: 将查询替换为以下内容:
string ab = string.Format( "insert into Hello values({0}, '{1}')", int.Parse( textBox1.Text ), textBox2.Text ); string ab = string.Format(“插入Hello值({0},'{1}')”,int.Parse(textBox1.Text),textBox2.Text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.