简体   繁体   中英

sql incorrect syntax near '.' when trying to use ExecuteNonQuery()

When I try to insert into my table's database I receive an SqlException pointing on the following code :

int x = 0;
{
   connect.Open(); //connect is an SqlConnection object
   x = command.ExecuteNonQuery();
}

the error points at the line where :

x = command.ExecuteNoneQuery;

saying that :

System.Data.SqlClient.SqlException: Incorrect syntax near ','.

here is the partial c# code: (the part which is relevant)

SqlConnection connect = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\thkiw\OneDrive\Documents\ilan.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand command = new SqlCommand("INSERT INTO profiles(userName , name , lastName , password , birthYear , birthMonth , birthDay , gender , email)" +
                                        "VALUES(" + user_name + "," + name  +"," + last_name + "," + password + "," + 
                                        year +","+ "," + month + "," + "day" + "," +
                                        (gender ? "1": "0")  +","+email + ")"

                                        , connect);                                   //GENDER is bit so 1 -true , 0 - false; (gender doesn't seem to convert automatically...)
    int x = 0;

    //try
    {
        connect.Open();
        x = command.ExecuteNonQuery();
    }
    /*catch (SqlException exception)
    {
        Session["lastException"] = exception;
        Session["source"] = "register.aspx";

        Response.Redirect("handleExceptions.aspx");
    }
    catch (Exception exception)
    {
        Session["lastException"] = exception;
        Session["source"] = "register.aspx";

        Response.Redirect("handleExceptions.aspx");
    }*/
    connect.Close();

    Response.Write("SUCCESS  - number of rows affected : " + x);

And this is the table schema

here is the table's code : (profiles)

CREATE TABLE [dbo].[profiles] (
[userName]   NCHAR (10) NOT NULL,
[name]       NCHAR (10) NULL,
[lastName]   NCHAR (10) NULL,
[birthDay]   INT        NULL,
[birthMonth] INT        NULL,
[birthYear]  INT        NULL,
[password]   NCHAR (15) NULL,
[gender]     BIT        NOT NULL,
[email]      NCHAR(20) NOT NULL,
PRIMARY KEY CLUSTERED ([userName] ASC)
);

Here's how you should handle inserting data into a query with parameters

SqlCommand command = new SqlCommand(
    "INSERT INTO profiles(userName, name, lastName, password, birthYear, birthMonth, birthDay, gender, email)" +
    "VALUES(@userName, @name, @lastName, @password, @birthYear, @birthMonth, @birthDay, @gender, @email)"
    , connect);
command.Parameters.Add("@userName", SqlDbType.NChar, 10).Value = user_name;
command.Parameters.Add("@name", SqlDbType.NChar, 10).Value = name;
command.Parameters.Add("@lastName", SqlDbType.NChar, 10).Value = last_name;
command.Parameters.Add("@password", SqlDbType.NChar, 10).Value = password;
command.Parameters.Add("@birthYear", SqlDbType.Int).Value = year;
command.Parameters.Add("@birthMonth", SqlDbType.Int).Value = month;
command.Parameters.Add("@birthDay", SqlDbType.Int).Value = day;
command.Parameters.Add("@gender", SqlDbType.Bit).Value = gender;
command.Parameters.Add("@email", SqlDbType.NChar, 10).Value = email;

This will avoid sql injection and handle formatting issues like the format of a DateTime or needing single quotes around a varchar value. Additionally it makes the query much cleaner and easier to spot issues like the two consecutive commas you have between the month and year.

You didn't enclose your values in single quotes.

However the best way is to use SQL Parameters. This prevents issues like this. https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx

This eliminates issues like this among other things like SQL injection. This is best practice.

command.Parameters.AddWithValue("@userName", user_name);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@lastName", last_name);
command.Parameters.AddWithValue("@password", password);
command.Parameters.AddWithValue("@year", year);
command.Parameters.AddWithValue("@month", month);
command.Parameters.AddWithValue("@day", day);
command.Parameters.AddWithValue("@gender", gender ? "1" : "0");
command.Parameters.AddWithValue("@email", email);

SqlCommand command = new SqlCommand("INSERT INTO profiles(userName , name , lastName , password , birthYear , birthMonth , birthDay , gender , email) VALUES(@userName , @name , @lastName , @password , @birthYear , @birthMonth , @birthDay , @gender , @email)", connect);         

When you run ExecuteNonQuery , you are invoking the command's commandText , which in your case was:

("INSERT INTO profiles(userName , name , lastName , password , birthYear , birthMonth , birthDay , gender , email)" +
                                        "VALUES(" + user_name + "," + name  +"," + last_name + "," + password + "," + 
                                        year +","+ "," + month + "," + "day" + "," +
                                        (gender ? "1": "0")  +","+email + ")"

                                        , connect); 

The error indicates that your query could not be processed because you have an error in the command. And, in that command, you have:

year +","+ "," + month +

Which has two commas being inserted in a row. It should be:

year + "," + month +

To avoid this string concatenation hell, you should really use SqlCommandParameter objects to configure your command. It also provides built-in protection against SQL Injection attacks.

Change sql command by below:

SqlCommand command = new SqlCommand("INSERT INTO profiles(userName , name , lastName , password , birthYear , birthMonth , birthDay , gender , email)" + "VALUES('" + user_name + "','" + name +"','" + last_name + '","' + password + "'," + year +","+ "," + month + "," + "day" + "," + (gender ? "1": "0") +",'"+email + "')"

                                    , connect);   

You forgot to add single quote both side in a character data like 'username'

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