简体   繁体   中英

Syntax error in INSERT INTO statement Insert in Access

I made a Accounts Project in c sharp with access2016 database, in this I want to enter user data in user management form when I click on save button this error appears

"System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement" in c#.

Here is my code;

public partial class frmUsers : MetroFramework.Forms.MetroForm
{
    OleDbConnection con = new OleDbConnection(ConfigurationManager.AppSettings ["con"]);
    OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DataBase.accdb;");

    public frmUsers()
    {
        InitializeComponent();
    }


    private void btnSave_Click(object sender, EventArgs e)
    {
        //string InsertPur= "insert into [Users] (UserCode,UserName,UserID,Password,Designation,ContactNo,UserType) values (" + txtUserCode.Text + ", '" + txtUserName.Text + "','" + txtUserID.Text + "','" + txtPassword.Text + "','" + txtDesignation.Text + "'," + txtContactNo.Text + ",'" + cboxUserType.Text + "')";
        OleDbDataAdapter da = new OleDbDataAdapter("insert into Users(UserCode,UserName,UserID,Password,Designation,ContactNo,UserType) values (" + txtUserCode.Text + ", '" + txtUserName.Text + "', '" + txtUserID.Text + "', '" + txtPassword.Text + "', '" + txtDesignation.Text + "', " + txtContactNo.Text + ", '" + cboxUserType.Text + "')", con);

        DataSet ds = new DataSet();
        da.Fill(ds);    //**Error Pointed here**
        ViewData();

        clearData();
        txtUserName.Focus();
    }
}

You have missed single quote around some of your textboxes like txtUserCode and ... it should be '" + txtUserCode + "' . However you should always use parameterized queries to avoid SQL Injection. Your code should be something like this:

OleDbDataAdapter da = new OleDbDataAdapter("insert into Users(UserCode,UserName,...) values"
                                                  + " (@UserCode,@UserName,...)", con);
da.InsertCommand.Parameters.AddWithValue("@UserCode", txtUserCode.Text);
//Other parameters

Although specify the type directly and use the Value property is more better than AddWithValue .

Can we stop using AddWithValue() already?

Your code has a formatting error that should be fixed if its the same as your real code :

in your textboxes you need to add single quote around your txtUserCode like this or it wont be registered as a whole parameter

'" + txtUserCode + "'

And your really shouldn't put your data directly into your query has it can lead to security issue and people injecting sql into it. Try and use parameterized queries instead when possible.Here is some reason why.

Why do we always prefer using parameters in SQL statements?

  • You need to use Parameters. Always specify the data type and pass the parameter value to match the schema store ( pass an integer as value if an integer is being stored ). Always specify the schema store length for the column if applicable like with a string/varchar.
  • You need to escape the column names so that the use of a reserved word does not cause an error.
  • You should not leave connections open when you are not using them.
  • (design) Never store passwords in plain text.
  • For an insert statement there is no need to use a Data Adapter, use the command object directly.

For Microsoft Access the parameters are positional based and not named, you should use ? as the placeholder symbol although the code would work if you used name parameters provided they are in the same order.

See the documentation for [OleDbCommand.Parameters Property][1]

Remarks

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

 SELECT * FROM Customers WHERE CustomerID = ? 

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

Be sure to include the expected schema type where the parameter will be used AND the schema length if applicable.

I also recommend you always use using statements around your instances where the type implements IDisposable like the OleDbConnection so that the connection is always closed even if an exception is thrown in the code.

Changed Code: I guessed on the data types and length, you should fix those based on the schema

using (var conn = new OleDbConnection(connectionStringHere))
using (var cmd = conn.CreateCommand())
{
    cmd.CommandText = "INSERT INTO Users([UserCode],[UserName],[UserID],[Password],[Designation],[ContactNo],[UserType]) VALUES (?,?,?,?,?,?,?)";

    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) {Value = txtUserCode.Text});
    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) {Value = txtUserName.Text});
    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) {Value = txtUserID.Text});
    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) {Value = txtPassword.Text});
    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) {Value = txtDesignation.Text});
    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.Integer) {Value = int.Parse(txtContactNo.Text) });
    cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) {Value = cboxUserType.Text});

    conn.Open();
    var numberOfRowsInserted = cmd.ExecuteNonQuery();
}

密码是Access SQL中的保留字,因此请在字符串中使用[Password]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM