我构建了一个 C# 应用程序,您可以在其中登录并注册新帐户。但是,当我单击“新帐户”按钮并填写必填字段时,我会收到以下错误:
vcom.ExecuteNonQuery(); -> OleDBException 未处理。指令 INSERT 包含语法错误。
请参阅下面的代码:
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 Eindopdracht
{
public partial class maak_account : Form
{
OleDbConnection vcon = new OleDbConnection(@"provider= microsoft.jet.oledb.4.0;data source=sample.mdb");
public maak_account()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection vcon = new OleDbConnection(@"provider= microsoft.jet.oledb.4.0;data source=sample.mdb");
vcon.Open();
string test = string.Format("insert into inlog (PASSWORD, Username, leeftijd, gewicht) VALUES ('" + textBox2.Text + "','" + textBox1.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')");
OleDbCommand vcom = new OleDbCommand(test, vcon);
vcom.ExecuteNonQuery();
MessageBox.Show("Uw gegevens zijn opgeslagen");
vcom.Dispose();
}
}
}
最佳答案
语法错误的原因是因为Password
(恰好是列名)是保留关键字。
insert into inlog ([PASSWORD], Username, leeftijd, gewicht)
来自 MS Access 文档,
If a reserved word is already in use, you can avoid error messages by surrounding each occurrence of the word with brackets ([ ]). However, the best solution is to change the name to a nonreserved word.
为了进一步改进代码,
- 使用
using
语句正确处置对象 - 使用
try-catch
正确处理异常 - 参数化值以避免 SQL 注入(inject)
示例,
string connStr = @"provider= microsoft.jet.oledb.4.0;data source=sample.mdb";
string test = "insert into inlog ([PASSWORD], Username, leeftijd, gewicht) VALUES (?, ?, ?, ?)";
using(OleDbConnection vcon = new OleDbConnection(connStr))
{
using(OleDbCommand vcom = new OleDbCommand(test, vcon))
{
vcom.Parameters.AddWithValue("PASSWORD", textBox2.Text);
vcom.Parameters.AddWithValue("Username", textBox1.Text);
vcom.Parameters.AddWithValue("leeftijd", textBox3.Text);
vcom.Parameters.AddWithValue("gewicht", textBox4.Text);
try
{
vcon.Open();
com.ExecuteNonQuery();
}
catch(OleDbException ex)
{
// do something with the exception
}
}
}
关于c# - OleDBException 错误插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15656936/