Click here to Skip to main content
15,395,257 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Error: System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'nvarchar'. Incorrect syntax near 'ID'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 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.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at registration.Button1_Click(Object sender, EventArgs e) in C:\Users\rache\source\repos\projectRegistration\registration.aspx.cs:line 51 ClientConnectionId:32e320e5-75e0-4fa2-8d6d-1193731f76c8 Error Number:102,State:1,Class:15

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class registration : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
            string checkuser = " select count(*) from [UserData] where Firstname= '" + TextBoxFname.Text + " '";
            SqlCommand com = new SqlCommand(checkuser, conn);
            int temp = Convert.ToInt32(com.ExecuteScalar().ToString());

            if (temp == 1)
            {
                Response.Write("User Already Exits");
            }
            conn.Close();
        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try { 
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
        conn.Open();
        string insertQuery = " insert into UserData (School ID, Firstname, Lastname, Age, Address, Mobile no., Gender) values (@School ID, @fname, @lname, @age, @Address, @phone, @Gender)";
        SqlCommand com = new SqlCommand(insertQuery, conn);

        com.Parameters.AddWithValue("@School ID", TextBoxID.Text);
        com.Parameters.AddWithValue("fname", TextBoxFname.Text);
        com.Parameters.AddWithValue("@lname", TextBoxLname.Text);
        com.Parameters.AddWithValue("@age", TextBoxAge.Text);
        com.Parameters.AddWithValue("@Address", TextBoxAddress.Text);
        com.Parameters.AddWithValue("@phone", TextBoxMobile.Text);
        com.Parameters.AddWithValue("@Gender", DropDownListGender.SelectedItem.ToString());


        com.ExecuteNonQuery();

        Response.Redirect("Default.aspx");
        Response.Write("Your Registration is successful");

        conn.Close();
    }
    catch(Exception ex)
    {
        Response.Write("Error: " + ex.ToString());

    }
}
}
Posted
Updated 12-Jun-22 5:34am
v2

Two things, starting with the one you haven't noticed yet because it's a lot more critical.

Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
Sort that throughout your whole app urgently first, then read on.

The other is simple: spaces are not allowed in column names and neither are punctuation characters, unless the name is escaped each time you use it in an SQL command:
SQL
insert into UserData (School ID, Firstname, Lastname, Age, Address, Mobile no., Gender) values (@School ID, @fname, @lname, @age, @Address, @phone, @Gender)
School ID and Mobile no. are both illegal and would need either changing to SchoolID and MobileNo or escaping with square brackets:
SQL
insert into UserData ([School ID], Firstname, Lastname, Age, Address, [Mobile no.], Gender) values (@School ID, @fname, @lname, @age, @Address, @phone, @Gender)
Spaces are not allowed at all in variable names and cannot be escaped, so @School ID needs the space removed everyu time you try to use it.
   
Comments
Richel Debalucos 13-Jun-22 0:02am
   
Thank you..
OriginalGriff 13-Jun-22 0:45am
   
You're welcome!
Quote:
Error: System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'nvarchar'. Incorrect syntax near 'ID'.

C#
string insertQuery = " insert into UserData (School ID, Firstname, Lastname, Age, Address, Mobile no., Gender) values (@School ID, @fname, @lname, @age, @Address, @phone, @Gender)";

Are you sure spaces and points are allowed in field names ?
   
Comments
Richel Debalucos 13-Jun-22 0:03am
   
Thank you..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900