0
[WebMethod] 
public void RegisterStudent(string Name, string Gender, int Marks)        
{            
    string connectionString = 
           "Data Source =SAJID-PC\\SQLEXPRESS;Initial Catalog=Design;Integrated Security=True";             
    SqlConnection con = new SqlConnection(connectionString);             
    con.Open();             
    String query = "INSERT INTO Students VALUES + ('" + Name + "', '" + Gender + "'," + Marks + ")";             
    SqlCommand sqlcom = new SqlCommand(query, con);
    sqlcom.ExecuteNonQuery();  
    con.Close();
}

I get this error when I invoke the method:

System.Data.SqlClient.SqlException: Incorrect syntax near '+'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Assignment4Web.StudentService.RegisterStudent(String Name, String Gender, Int32 Marks) in c:\users\sajid\documents\visual studio 2010\Projects\Assignment4Web\Assignment4Web\StudentService.asmx.cs:line 56

0

1 Answer 1

3

Remove unnecessary + after Values and add ' around Marks like this:

String query = "INSERT INTO Students VALUES ('" + Name + "', '" + Gender + "','" + Marks + "')";

Although you should always use parameterized queries to avoid SQL Injection. Something like this:

SqlCommand sqlcom = new SqlCommand("INSERT INTO Students VALUES(@Name ,@Gender,@Marks");
cmd.Parameters.AddWithValue("@Name",Name);
cmd.Parameters.AddWithValue("@Gender",Gender);
cmd.Parameters.AddWithValue("@Marks",Marks);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.