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

-2

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.

c#
sql
visual-studio-2017
asked on Stack Overflow Mar 22, 2019 by Noam Yizraeli • edited Mar 22, 2019 by marc_s

1 Answer

0

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.

answered on Stack Overflow Mar 22, 2019 by yv989c

User contributions licensed under CC BY-SA 3.0