gpt4 book ai didi

c# - OleDBException 错误插入

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:33 26 4
gpt4 key购买 nike

我构建了一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com