-1

I'm trying to get my program to make an entry into my SQL Server database but when I run it I get an error saying incorrect syntax near ')'.

SqlConnection conn = new SqlConnection("Data Source=AJ-PC;Initial Catalog=Customers;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customers ('1', '1', '1', '1000/01/01', '1', '1')", conn);
cmd.ExecuteNonQuery();
conn.Close();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • _"Questions seeking debugging help ("why isn't this code working?") must include the desired behavior"_ –  Jan 12 '15 at 06:30
  • 1
    You'd also be better learning the right way to do it using parameters, see the following answer for example: http://stackoverflow.com/a/19956944/1599751 – PeterJ Jan 12 '15 at 06:31

5 Answers5

0

It should be:

SqlCommand cmd = new SqlCommand("INSERT INTO Customers(col1, col, col3, ....) VALUES ('1', '1', '1', '1000/01/01', '1', '1')", conn);
                                                                              ******

You need to specify the VALUES keyword, and I would also recommend to always specify the explicit list of columns in the table you're inserting into.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

You missed the VALUES keyword in the query

INSERT INTO Customers VALUES ('1', '1', '1', '1000/01/01', '1', '1')
Saravana Kumar
  • 3,669
  • 5
  • 15
  • 35
0

Do it like this:

SqlCommand cmd = new SqlCommand("INSERT INTO Customers (column names...) values('1', '1', '1', '1000/01/01', '1', '1')",con);

You are not specifying column names and Values Keyword.

Badrul
  • 1,582
  • 4
  • 16
  • 27
0

I know this answers the question in a bit different way. But this is for the future reference. I would suggest you to use try...catch...finally block.

SqlCommand cmd;
try {
    conn.Open();
    string query = "INSERT INTO Customers (col1, col2, col3,...) VALUES ('val1', 'val2', 'val3',...)";
    cmd = new SqlCommand(query, conn);
    int RowsAffected = cmd.ExecuteNonQuery();
    if(RowsAffected > 0) {
    //If you are on Console:
    Console.WriteLine("1 Row Inserted");

    //If you are on WinForms / WebForms:
    lblMessage.Text = "1 Row Inserted";
} catch (Exception ex) {
    //If you are on Console:
    Console.WriteLine("Some Exception: " + ex.Message.ToString());

    //If you are on WinForms / WebForms:
    lblMessage.Text = "Some Exception: " + ex.Message.ToString();
} finally {
    conn.Close();
}
Saiyan Prince
  • 3,930
  • 4
  • 28
  • 71
  • or better yet: put your `SqlConnection` and `SqlCommand` into `using (...) { ...... }` blocks! – marc_s Jan 12 '15 at 06:55
0

You mave missed including "VALUES" clause in your command. You would use it as below

Insert into Table_Name(Col1,Col2,...ColN) VALUES (VAL1,VAL2,...VAL3)

where, Table_Name- Your Table name Col1,Col2,...ColN- Column names in your table VAL1,VAL2,...VAL3- Values supplied to respective columns

Hope this works for you

Praveen
  • 86
  • 1
  • 9