Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write SQL Query in C# code with multiple lines

Tags:

c#

sql

c#-4.0

I'm writing a SQL query in C# code. But it is giving an errors. How can I correct this?

private string sql = "";
sql = (@"insert into employee_master
(
NATIONALITY,RELIGION,BLOODGROUP,
ELECTORATE,PROVINCE,DISTRICT,MOBILE
)
values
(
'"+emp.NATIONALITY+"','"+emp.RELIGION+"','"+emp.BLOODGROUP+"',
'"+emp.ELECTORATE+"','"+emp.PROVINCE+"','"+emp.DISTRICT+"','"+emp.MOBILE+"'
)");

enter image description here

like image 459
Tom Avatar asked Jan 17 '26 06:01

Tom


1 Answers

You should really remove that string concatenation and use a parameterized query. I can only suppose, from your short code, that something is not as you (or the compiler) expect in that string values that you stick together with quotes. For example, if one of your string values contains a single quote, the whole query will fail with a Syntax Error. A parameterized query, instead, removes any problem with quotes and render your query safe from Sql Injections (and it is a lot easier to understand what's going on)

private string sql = "";
sql = @"insert into employee_master
(
    NATIONALITY,RELIGION,BLOODGROUP,
    ELECTORATE,PROVINCE,DISTRICT,MOBILE
)
values
(
    @nat,@rel,@blood,
    @elect,@prov,@district,@mobile
)";

using (SqlConnection con = new SqlConnection(...constring here...))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
    con.Open();
    cmd.Parameters.Add("@nat", SqlDbType.NVarChar).Value = "Nationality";
    ... continue adding other parameters like @rel, @blood etc... and their values
    cmd.ExecuteNonQuery();
}

Said that, after your edit, we can easily see the error pointed by the red squiggles. It is caused by the bad line endings on these lines

....'"+emp.BLOODGROUP+"',
....'"+emp.MOBILE+"'

you should change them to

....'"+emp.BLOODGROUP+"',"
....'"+emp.MOBILE+"'"

to be correct for the compiler. The effect of the verbatim character @ is terminated when you use the + operator to concatenate strings and you need to repeat it again if you want to omit the closing double quote on the lines above. This leads to this terrible and error prone syntax:

....'"+emp.BLOODGROUP+ @"',
....'"+emp.MOBILE+ @"'

But again, this doesn't protect you from malformed input values that could generate an exception or be a catastrophic hacking of your program. So, please do not write queries in this way

like image 58
Steve Avatar answered Jan 19 '26 20:01

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!