简体   繁体   中英

Incorrect syntax near 'nvarchar'. SQL Server Error

I am trying to enter data using query string. My code is

    protected void Page_Load(object sender, EventArgs e)
    {
      //  insertData();
        if (!String.IsNullOrWhiteSpace(Request.QueryString["SChn"]))
            {
                if (!String.IsNullOrWhiteSpace(Request.QueryString["PAN"]))
                    {
                        if (!String.IsNullOrWhiteSpace(Request.QueryString["STag"]))
                            {
                                if (!String.IsNullOrWhiteSpace(Request.QueryString["MAC"]))
                                    {
                                        insertData1();
                                    }
                             }
                    }
            }
    }
        //   else
        //  {
        //         Response.Redirect("http://localhost:53627/Default.aspx");
        //   }



    public void insertData1()
    {
        using (SqlConnection con = new SqlConnection(GetConnectionString()))
        {
            con.Open();
            try
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO SensorConfig(SChn, PAN, STag, MAC) VALUES(@SChn, @PAN, @STag, @MAC)", con))
                {

                    cmd.Parameters.Add(new SqlParameter("SChn", Request.QueryString["SChn"].Trim()));
                    cmd.Parameters.Add(new SqlParameter("PAN", Request.QueryString["PAN"].Trim()));
                    cmd.Parameters.Add(new SqlParameter("STag", Request.QueryString["STag"].Trim()));
                    cmd.Parameters.Add(new SqlParameter("MAC", Request.QueryString["MAC"].Trim()));
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception Ex)
            {
                // Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
                Response.Write("Unable To Save Data. Error - " + Ex.Message);
            }
        }

    }
    public string GetConnectionString()
    {
        //sets the connection string from the web config file "ConnString" is the name of the Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        insertData1();
    }

I made some changes according to the suggestions but the error changed to

Error - Object reference not set to an instance of an object. I tried but not getting any clue.

You used wrong sql parameter names

cmd.Parameters.Add(new SqlParameter("@SChn", Request.QueryString["SChn"]));
cmd.Parameters.Add(new SqlParameter("@PAN", Request.QueryString["PAN"]));
cmd.Parameters.Add(new SqlParameter("@STag", Request.QueryString["STag"]));
cmd.Parameters.Add(new SqlParameter("@MAC", Request.QueryString["MAC"]));

you need to specify exact same names as in sql query

EDIT

add this before, if you pass normal null or empty value, you will get your error, so you need to pass DBNull.Value instead

if(string.IsNullOrWhitespace(Request.QueryString["SChn"]))
{
    cmd.Parameters.Add(new SqlParameter("@SChn", DBNull.Value);
}
else
{
    cmd.Parameters.Add(new SqlParameter("@SChn", Request.QueryString["SChn"]));
}

EDIT2

if your columns are not null columns change your code to:

    if (!String.IsNullOrWhitespace(Request.QueryString["SChn"]))
    {
        if (!String.IsNullOrWhitespace(Request.QueryString["PAN"]))
        {
            if (!String.IsNullOrWhitespace(Request.QueryString["Stag"]))
            {
                if (!String.IsNullOrWhitespace(Request.QueryString["MAC"]))
                {
                    insertData();
                }
            }
        }
    }

because you want to add values only when they are not null and not empty

Change this code part. You should specify parameter name, not the column name.

cmd.Parameters.Add(new SqlParameter("@SChn", Request.QueryString["SChn"]));
cmd.Parameters.Add(new SqlParameter("@PAN", Request.QueryString["PAN"]));
cmd.Parameters.Add(new SqlParameter("@STag", Request.QueryString["STag"]));
cmd.Parameters.Add(new SqlParameter("@MAC", Request.QueryString["MAC"]));

EDIT:

Some values can be empty string. You should change this code too

if (!String.IsNullOrEmpty(Request.QueryString["SChn"]))
        {
            if (!String.IsNullOrEmpty(Request.QueryString["PAN"]))
            {
                if (!String.IsNullOrEmpty(Request.QueryString["Stag"]))
                {
                    if (!String.IsNullOrEmpty(Request.QueryString["MAC"]))
                    {
                        insertData();
                    }
                }
            }
        }

More info on this

SqlCommand.Parameters Property

Problem : you should provide the Command Parameters which are specified in SQL INSERT INTO Statement

You have given used insert into as below:

"INSERT INTO SensorConfig(Sensor_Channel, PAN_ID, SENSOR_TAG, MAC_Address) VALUES(@SChn, @PAN, @STag, @MAC)"

So you should provide as below:

cmd.Parameters.Add(new SqlParameter("@SChn", Request.QueryString["SChn"]));
cmd.Parameters.Add(new SqlParameter("@PAN", Request.QueryString["PAN"]));
cmd.Parameters.Add(new SqlParameter("@STag", Request.QueryString["STag"]));
cmd.Parameters.Add(new SqlParameter("@MAC", Request.QueryString["MAC"]));
cmd.ExecuteNonQuery();

Solution 2: I think your 3rd Query String is Request.QueryString["Stag"] small s not Capital S Check it once

Solution 3: change if conditions as below:

if ((Request.QueryString["SChn"] != null) && (!(Request.QueryString["SChn"].Trim().Equals(""))))
{
   if ((Request.QueryString["PAN"] != null) && (!(Request.QueryString["PAN"].Trim().Equals(""))))
   {
      if ((Request.QueryString["STag"] != null) && (!(Request.QueryString["STag"].Trim().Equals(""))))
      {
         if ((Request.QueryString["MAC"] != null) && (!(Request.QueryString["MAC"].Trim().Equals(""))))
         {
            insertData();
         }
      }
   }
}

while inserting data use Trim

cmd.Parameters.Add(new SqlParameter("@SChn", Request.QueryString["SChn"].Trim()));
cmd.Parameters.Add(new SqlParameter("@PAN", Request.QueryString["PAN"].Trim()));
cmd.Parameters.Add(new SqlParameter("@STag", Request.QueryString["STag"].Trim()));
cmd.Parameters.Add(new SqlParameter("@MAC", Request.QueryString["MAC"].Trim()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM