Error while trying insert values into a database table. Help!

I keep getting an error that says Incorrect syntax near ','. When I try to insert values into a database table. Here's the code:

===================================================================

using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;


public class MemberFileReader
{
private MemberFileReader()
{
}


public static void ParsePositional(string FileName)
{

String strSQLInsert = "INSERT INTO Members VALUES(" +
tempCType+ "," +tempNRDS+ "," +tempLastName+ "," +
tempFirstName+ "," +tempMiddleName+ "," +tempStatus+ "," +
tempEmail+ ")";


System.Data.SqlClient.SqlConnection connStr =
new System.Data.SqlClient.SqlConnection();


connStr.ConnectionString = "data source=WALTERPPK\SQLEXPRESS;Integrated Security=True;AttachDBFilename=C:\\Documents and Settings\\ugo\\My Documents\\Visual Studio 2005\\Projects\\DataExchange_3\\DataExchange_3\\stlCR_temp.mdf;user instance=true";


System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = strSQLInsert;
cmd.Connection = connStr;

connStr.Open();

cmd.ExecuteNonQuery();

connStr.Close();

}

}

==============================================================

Any ideas
Thx





Answer this question

Error while trying insert values into a database table. Help!

  • royalhale

    You need to put single quotes, like ', around field values that are of type string.



  • M Thomas

    Best approach is to use parameterized query. In this case you do not need to escape any special characters and you will avoid SQL injection. Code will contain more lines, but it worth it.

  • jshepler

    Thanks Guys/Gals.

    I updated the strings in the code and it worked.


  • chakravarthy_b

    Yes it should be:

    String strSQLInsert = "INSERT INTO Members VALUES('" +
    tempCType+ "', '" +tempNRDS+ "', '" +tempLastName+ "', '" +
    tempFirstName+ "', '" +tempMiddleName+ "', " +tempStatus+ ", '" +
    tempEmail+ "')";

    But you're syntax for your insert is also incorrect...it should be:

    String strSQLInsert = "INSERT INTO Members(Ctype, NRDS, LastName, FirstName, MiddleName, Status, Email)

    VALUES(' +
    tempCType+ ", '" +tempNRDS+ "', '" +tempLastName+ "', '" +
    tempFirstName+ "', '" +tempMiddleName+ "', " +tempStatus+ ", '" +
    tempEmail+ "')";

    The above assumes tempCtype and tempStatus are not strings.

    Adamus



  • Error while trying insert values into a database table. Help!