Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error with inserting sql into access db using C# and asp.net

I get an error on the line

cmd.ExecuteNonQuery();

which says

Syntax error in INSERT INTO statement

I think my query should be valid, I don't understand the problem and I've been working on it for hours. It's in the right order and putting [] around Users did not work for me, would appreciate help.

<%@ Page Language ="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>   
    <script runat="server">
    protected void Page_Load()
    {

            String username = Request.Form["username"];
            String email = Request.Form["email"];
            String password = Request.Form["password1"];
            var age = Request.Form["age"];
            String country = Request.Form["country"];
            String hobbie = Request.Form["skin"];
            String sql;

            sql = "INSERT INTO Users(UserName, Email, Password, Age, Country, Hobbie) VALUES('" + username + "','" + email + "','" + password + "'," + age + ",'" + country + "','" + skin + "')";

            String Path = Server.MapPath("App_Data/Users.accdb");
            String connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Path;

            OleDbConnection conn = new OleDbConnection(connStr);
            conn.Open();

            OleDbCommand cmd = new OleDbCommand(sql, conn);
            cmd.ExecuteNonQuery();

            conn.Close();
    }
like image 940
TG Person Avatar asked Mar 20 '23 18:03

TG Person


1 Answers

PASSWORD is a reserved keyword for MS-Access. Use it enclosed in square brackets

    sql = "INSERT INTO Users(UserName, Email, [Password] ....

But please, change that sql text to use a parameterized query. Also, if you are able to send this command with the actual values your query remains open to Sql Injection vulnerability and a parsing problem could arise when your input string contains a single quote

   sql = @"INSERT INTO Users(UserName, Email, [Password], Age, Country, Hobbie) 
           VALUES(?,?,?,?,?,?)";
   ....

   OleDbCommand cmd = new OleDbCommand(sql, conn);
   cmd.Parameters.AddWithValue("@p1", username);
   .... and so on for the other 5 parameters required by the query ....
like image 133
Steve Avatar answered Mar 22 '23 19:03

Steve