简体   繁体   中英

Incorrect syntax near ','. error

I am getting an SQL error when I try to do this:

    public static int GetOrderId(decimal totalprice, int userid)
    {
        string s = "SELECT * from orders where OrderUserId = " + userid + " and OrderTotalPrice = " + totalprice;
        cmd = new SqlCommand(s, con);
        int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

        return temporderid;
    }

As far I can see its because it gets OrderTotalPrice back, the format is incompatible. But I cant figure out how to get it in the compatible format.

It's probably formatting totalprice with a comma, like 3,14 , where SQL Server expects a dot, like 3.14 .

One way to fix that would be to specify InvariantCulture, which uses a dot:

var s = string.Format(
    CultureInfo.InvariantCulture, 
    "SELECT * from orders where OrderUserId = {0} and OrderTotalPrice = {0:0.0}",
    42, 3.1415);

This formats the price as 3.1 on any machine.

By the way, it's much nicer to pass the variables as parameters:

var com = new SqlCommand();
com.CommandType = CommandType.Text;
com.CommandText = "SELECT * from orders where OrderUserId = @userid " +
    "and OrderTotalPrice = @totalprice";
com.Parameters.AddWithValue("@userid", 42);
com.Parameters.AddWithValue("@totalprice", 3.1415);
var temporderid = com.ExecuteScalar();

Then you don't have to worry about formats because you send the database a double, not a double formatted as a string.

I guess this is because totalprice gets converted to something like 12,35 when you concatenate the query.

Therefore, I'd suggest you use a parametrized query. Eg like this:

var s = "SELECT * from orders " +
    " where OrderUserId = @userid and OrderTotalPrice = @totalprice";
var cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("userid", userid);
cmd.Parameters.AddWithValue("totalprice", totalprice);

int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

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