2

I get this error when I try to insert data into database

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'Name'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.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at adduser.Button1_Click(Object sender, EventArgs e) in c:\Users\Ibtisam Tanveer\Documents\Visual Studio 2012\WebSites\WebSite1\adduser.aspx.cs:line 53 ClientConnectionId:df4aec92-1f96-4236-9bd7-f802a52b5213 Error Number:102,State:1,Class:15

My code:

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 adduser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SqlConnection conec = new SqlConnection(ConfigurationManager.ConnectionStrings["DonorInformationConnectionString"].ConnectionString);
            conec.Open();
            string checkuserCNIC = "select count(*) from Donor where CNIC='" + TextBoxCNIC.Text + "'";
            SqlCommand com = new SqlCommand(checkuserCNIC,conec);
            int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
            if (temp == 1)
            {
                Response.Write("User Already Exists");
            }

            conec.Close();
            
        }

    }
    protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conec = new SqlConnection(ConfigurationManager.ConnectionStrings["DonorInformationConnectionString"].ConnectionString);
            conec.Open();
            string insertquerry = "insert into Donor(First Name, Last Name, Cell number, Email, CNIC, City, Address, Blood Group, Gender, Password) values (@firstname, @lastname, @cell, @email, @cnic, @city, @address, @blood, @sex, @password)";
            SqlCommand com = new SqlCommand(insertquerry, conec);
            com.Parameters.AddWithValue("@firstname", TextBoxFirst_Name.Text);
            com.Parameters.AddWithValue("@lastname", TextBoxLast_Name.Text);
            com.Parameters.AddWithValue("@cell", TextBoxPhone.Text);
            com.Parameters.AddWithValue("@email", TextBox_Email.Text);
            com.Parameters.AddWithValue("@cnic", TextBoxCNIC.Text);
            com.Parameters.AddWithValue("@city", DropDownList_City.SelectedItem.ToString());
            com.Parameters.AddWithValue("address", TextBox_Address.Text);
            com.Parameters.AddWithValue("@blood", DropDownListBloodGroup.SelectedItem.ToString());
            com.Parameters.AddWithValue("@sex", DropDownList_Gender.SelectedItem.ToString());
            com.Parameters.AddWithValue("@password", TextBoxCNIC.Text);
            com.ExecuteNonQuery();
            Response.Write("Donor Added Successfully");
            conec.Close();
        }
        catch(Exception ex)
        {
            Response.Write("There is some Errors Please Read------------------>" + ex.ToString());
        }

            
    }
    protected void DropDownList_Gender_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
2
  • Welcome to StackOverflow! What have you tried yourself? Or is this going to be some challenge for us? Please read How to ask, and SSCCE Commented Jan 22, 2015 at 10:21
  • Thank you for your correction I will consider these things in my next question. Commented Jan 22, 2015 at 10:33

1 Answer 1

3

use this First Name like [First Name] and other columns too.

You should always use [] if you have space in column name. Also you should be avoiding space in column names.

So your code becomes

string insertquerry = "insert into Donor([First Name], [Last Name], 
    [Cell number], Email, CNIC, City, Address, Blood Group, Gender, 
    Password) values (@firstname, @lastname, @cell, @email, @cnic, @city, 
     @address, @blood, @sex, @password)";
Sign up to request clarification or add additional context in comments.

2 Comments

Using the [] around your field names will also escape out fields that share their names with keywords in SQL. Ie: Select ID, [From] from [Table] (that's an example of extremely bad field name but it happens)
Thank you exception removed now

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.