Clem
Clem

Reputation: 11824

C# update database

I'm using this string to update database and in this case, it works fine. It updates Znesek_nakupa in in last row:

string sqlUpd = "UPDATE Racun SET Znesek_nakupa='10' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";

But when I'm trying to insert variable and not just 10 it gives me error:

Error converting data type varchar to numeric.

Code example:

double totalPrice = 1.1;
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='totalPrice' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";

How can I do this?

Upvotes: 0

Views: 2043

Answers (2)

Clem
Clem

Reputation: 11824

Ok, I got it. When I try to save variable totalPrice in database it comes to error, because C# has comma as separator. In database I have to send dot instead. So I simple replace comma with dot and now it works perfect.

So code looks like this now:

string sqlUpd = "UPDATE Racun SET Znesek_nakupa='" + Convert.ToString(totalPrice).Replace(',', '.') + "' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";

Upvotes: 0

Richard Ev
Richard Ev

Reputation: 54087

This problem less to do with SQL, and more to do with using strings and variables in C#.

In order to insert the value of a variable in a string in C#, you can't just place the name of the variable in the string. The string doesn't "know" that it contains a variable. Here are a couple of approaches that will work instead:

double totalPrice = 1.1;

// string concatenation
string sqlUpd =
    "UPDATE Racun SET Znesek_nakupa='" +
    totalPrice +
    "' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";

// with string.Format
string sqlUpd = string.Format(
    "UPDATE Racun SET Znesek_nakupa='{0}' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)",
    totalPrice);

However, the approach of just embedding a variable's value in a SQL query like this is not considered best practice as it risks SQL injection attacks. Usually you would want to use parameterised SQL queries.

A parameterised version of your query would look like this (lifting the example from the page linked to above):

SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
string s = "UPDATE Racun SET Znesek_nakupa='@totalPrice' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("@totalPrice", totalPrice);
SqlDataReader reader = cmd.ExecuteReader();

Upvotes: 3

Related Questions