我构建了一个c#应用程序,您可以在其中登录并注册一个新帐户。但是,当我点击我的按钮新帐户,并填写必填字段时,我将收到以下错误:
vcom.ExecuteNonQuery(); - > OleDBException未处理。 INSERT指令包含syntaxerror。
请参阅下面的代码:
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();
}
}
}
答案 0 :(得分:2)
语法错误的原因是因为Password
恰好是列的名称,是保留关键字。
insert into inlog ([PASSWORD], Username, leeftijd, gewicht)
来自MS Access Docs,
如果已使用保留字,则可以避免出现错误消息 用括号([])围绕每个单词的出现。然而, 最好的解决方案是将名称更改为非保留字。
为了进一步改进代码,
using
语句来正确处置对象try-catch
来正确处理异常例如,
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
}
}
}
答案 1 :(得分:0)
使用try / catch块捕获异常并查看errormessage。还要在finally块中处理您的资源。即使抛出异常,也会始终执行finally块。
try
{
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");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
vcom.Dispose();
vcon.Close();
vcon.Dispose();
}