Reputation: 57
I have some problem when I want to insert data into database ACCESS using C#
The message error is:
System.data.OleDb.OleDbException (0x80040E14): error de syntaxe dans l'instruction INSERT INTO...........
Does someone know what the problem is?
Here 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.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);
}
}
}
}
Upvotes: 0
Views: 491
Reputation: 98740
Besides on your insert values, I think this happens because Password
is a reserved keyword in OLE DB Provider. You should use it with square brackets like [Password]
. The best solution is to change your column name to a non-reserved word.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. You don't need to use String.Format
in your case as well since you didn't format your string.
Also use using
statement to dispose your OleDbConnection
and OleDbCommand
.
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.
}
Upvotes: 4
Reputation: 89
Password is a reserved words in Access. Try the Query like this:
command.CommandText = String.Format(@"INSERT INTO [membre] (Player, [Password], Gun, Claass) VALUES('" + player.Text + "', '" + password.Text + "', '" + gun.Text + "', '" + kind.Text + "')");
Upvotes: 0