简体   繁体   中英

SQL exception incorrect syntax near 'G' what's the problem?

I have a SQL query created by inserting values from C#.

In C#:

string command = "INSERT INTO Phones (devicename, batterylife, price, antutu, ImageURL) 
                  VALUES (" + model + ", " + batterylife + ", " + price + ", " + antutu + ", " + imgURL + " )";

In SQL after parsing:

INSERT INTO Phones (devicename, batterylife, price, antutu, ImageURL) 
VALUES ( Samsung-Galaxy-S10-5G, 0, 0, 0, 
         cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s10-5g.jpg )

and when trying to execute it, Visual Studio throws the following exception:

System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Incorrect syntax near 'G'.
Source=.Net SqlClient Data Provider

Also when I replace the regular model name variable with a word Visual Studio throws the same exception for little g with no location help to understand.

As others have indicated, you are using string concatenation to build your SQL command, which will enable SQL injection in your code.

Please use the following pattern instead which relies on parameters and therefore is not susceptible to this attack:

using System.Data.SqlClient;
using System.Data;
...
using (var cn = new SqlConnection("YourConnectionString"))
{
    cn.Open();

    using (var cm = cn.CreateCommand())
    {
        cm.CommandType = System.Data.CommandType.Text;
        cm.CommandText =
            "INSERT INTO Phones (devicename, batterylife, price, antutu, ImageURL) " +
            "VALUES (@devicename, @batterylife, @price, @antutu, @ImageURL)";

        cm.Parameters.Add("@devicename", SqlDbType.VarChar, 50).Value = "Samsung-Galaxy-S10-5G";
        cm.Parameters.Add("@batterylife", SqlDbType.Int).Value = 0;
        cm.Parameters.Add("@price", SqlDbType.Int).Value = 0;
        cm.Parameters.Add("@antutu", SqlDbType.Int).Value = 0;
        cm.Parameters.Add("@ImageURL", SqlDbType.VarChar, -1).Value = "cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s10-5g.jpg";

        cm.ExecuteNonQuery();
    }
}

You must adjust the size/type of each SqlParameter as needed.

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