语法错误插入数据库

时间:2014-12-31 10:28:43

标签: c# ms-access

当我想使用C#

将数据插入数据库ACCESS时,我遇到了一些问题

消息错误是:

  

System.data.OleDb.OleDbException(0x80040E14):error de syntaxe dans l' instruction INSERT INTO ...........

有人知道问题是什么吗?

这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Windows.Forms;

namespace First_cnx
{
    public partial class Form2 : Form
    {
        private OleDbConnection connection = new OleDbConnection();
        public Form2()
        {
            InitializeComponent();
            connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Reeda\Documents\Warface.accdb;
Persist Security Info=False;";
        }

        private void save_Click(object sender, EventArgs e)
        {
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                command.CommandText = String.Format(@"INSERT INTO [membre] (Player, Password, Gun, Claass) VALUES('" + player.Text + "', '" + password.Text + "', '" + gun.Text + "', '" + kind.Text + "')");

                command.ExecuteNonQuery();
                MessageBox.Show("Data Saved !");
                connection.Close();
            }
            catch (Exception ex) {
                MessageBox.Show("Error " + ex);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:4)

除了插入值之外,我认为这是因为Password是OLE DB提供程序中的reserved keyword。您应该使用方括号(如[Password])。最佳解决方案是将列名更改为非保留字。

但更重要的是

您应始终使用parameterized queries。这种字符串连接对SQL Injection攻击是开放的。您也不需要在案例中使用String.Format,因为您没有格式化字符串。

还可以使用using statement来处置您的OleDbConnectionOleDbCommand

using(OleDbConnection connection = new OleDbConnection(conString))
using(OleDbCommand command = connection.CreateCommand())
{
    // Set your CommandText property.
    // Define and add your parameter values.
    // Open your OleDbConnection.
    // Execute your query.
}

答案 1 :(得分:0)

密码是reserved words in Access。像这样尝试查询:

command.CommandText = String.Format(@"INSERT INTO [membre] (Player, [Password], Gun, Claass) VALUES('" + player.Text + "', '" + password.Text + "', '" + gun.Text + "', '" + kind.Text + "')");