C# String literal with concatenation - c#

I have a ASP.NET C# application, and I frequently use the verbatim string literal such as
dbCommand.CommandText = #"INSERT INTO MYTABLE (COLUMN, COLUMN2)
VALUES ('data', 'data)";
This is all great, but when I try to concatenate the string with a variable such as
dbCommand.CommandText = #"INSERT INTO MYTABLE" + Session["table_extension"] + "(COLUMN, COLUMN2)
VALUES('data','data')";
I get an error stating Newline in constant. How can I avoid this while still using the # string literal?

Put the # in front of the second string literal or use String.Format()

1) Don't concatenate strings to build SQL commands, it's really dangerous and error phrone (see SQL Injection: http://www.w3schools.com/sql/sql_injection.asp).
You should use ADO.NET parameters (http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06)
2) If you are going to concatenate strings, use string.Format like:
var sql = string.Format("INSERT INTO MyTable ('col1') VALUES ({0})", col1Value);
Or use the new simplified syntax which has a better compile time check:
var sql = $"INSERT INTO MyTable (col1) VALUES ('{col1Value}')";

This will work for you!
dbCommand.CommandText = #"INSERT INTO MYTABLE" + Session["table_extension"].ToString() + "(COLUMN, COLUMN2)
VALUES('data','data')";

Related

I get an SQL syntax error when using this query

this works:
string sqlStr = string.Format("INSERT INTO tblFiles (filename,downloadname,description,category,length,parts,checksum,isEncrypted,uploaderIp) VALUES ('{0}','{1}','{2}','{3}',{4},{5},'{6}',{7},'{8}');",
newFile.Name.Replace("'", "''"), newFile.DownloadName.Replace("'", "''"), newFile.Description, newFile.Category, newFile.Length, newFile.Parts, newFile.Checksum, newFile.IsEncrypted, GetPeerIp());
this doesn't:
string sqlStr = string.Format("INSERT INTO tblFiles (filename,downloadname,description,category,length,parts,checksum,isEncrypted,password,uploaderIp) VALUES ('{0}','{1}','{2}','{3}',{4},{5},'{6}',{7},'{8}','{9}');",
newFile.Name.Replace("'", "''"), newFile.DownloadName.Replace("'", "''"), newFile.Description, newFile.Category, newFile.Length, newFile.Parts, newFile.Checksum, newFile.IsEncrypted, password, GetPeerIp());
Exception I get:
$exception {"Syntax error in INSERT INTO statement."} System.Exception {System.Data.OleDb.OleDbException}
my database looks like this.
I couldn't find any problem with it. Any ideas?
Thanks
Password is a reserved keyword in MS-Access sql. If you have a field with that name you need to encapsulate that name between square brackets (better change it now)
string sqlStr = #"INSERT INTO tblFiles
(filename,downloadname,description,category,length,parts,
checksum,isEncrypted,[password],uploaderIp) VALUES (.....)";
Said that, please, remove all that string concatenations and use a parameterized query. Not only this is more safe (prevents Sql Injections) but also removes all the problems with quoting and correct parsing of dates and decimal numbers
string sqlStr = #"INSERT INTO tblFiles
(filename,downloadname,description,category,length,parts,
checksum,isEncrypted,[password],uploaderIp) VALUES
(#file, #down, #desc, #cat, #len, #parts, #check, #enc, #pass, #up)";
OleDbCommand cmd = new OleDbCommand(sqlStr, connection);
cmd.Parameters.Add("#file", OleDbType.VarWChar).Value = newFile.Name;
cmd.Parameters.Add("#down", OleDbType.VarWChar).Value = newFile.DownloadName;
... and so on for all other parameters respecting the OleDbType of the column....
cmd.ExecuteNonQuery();
Notice how your query is more clear and understandable and how you don't need to call a lot of Replace just to get rid of possible embedded single quotes.

How to add one double-quotes (") to string?

I writing a request in C# for MySql Database and I need to write in string of the command double-quotes.
Something like:
String command ="Insert into table (column) values ("" + textBox1.Text + "")";
But I have a syntax error of C#. When I try chenge " to `
String command ="Insert into table (column) values ('" + textBox1.Text + "')";
I have a syntax error of Mysql(1054). Row column has a type varchar. How to correctly write this request in a program?
This is how:
string mystring = "We use \"a laser\"";
BUT! Since you are trying to form an sql query, you shouldn't do this yourself. You need to use sql parameters that will protect you from sql injection.
Here is a short lesson about sql parameters: http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

SQL server - inserting a string with a single quotation mark

I iterate over an external source and get a list of strings. I then insert them into the DB using:
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
Where commandString is an insert into command. i.e.
insert into MyTable values (1, "Frog")
Sometimes the string contains ' or " or \ and the insert fails.
Is there an elegant way to solve this (i.e. #"" or similar)?
Parameters.
insert into MyTable values (#id, #name)
And
int id = 1;
string name = "Fred";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("name", name);
command.ExecuteNonQuery();
Now name can have any number of quotes and it'll work fine. More importantly it is now safe from sql injection.
Tools like "dapper" (freely available on NuGet) make this easier:
int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (#id, #name)",
new { id, name });
You should look into using parameterized queries. This will allow you insert the data no matter the content and also help you avoid possible future SQL injection.
http://csharp-station.com/Tutorial/AdoDotNet/Lesson06
http://www.c-sharpcorner.com/uploadfile/puranindia/parameterized-query-and-sql-injection-attacks/

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?
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();
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)";

SQL INSERT - Invalid column name

As some of you may of seen from my previous post I'm new to using C# to create websites (Although I have a fair bit of experience using it for Windows Forms apps). The powers that be are tempting me away from PHP but I keep failing at what I consider the basics.
Anyway, this is my issue. I am trying to create a simple entry into a SQL database. I know my connection to the DB is fine as I can reel off SELECT queries all day long but I'm having trouble with using Insert.
Heres my code:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(//you dont need to see my data here ;));
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
SqlCommand sql = new SqlCommand(sqlcode,link);
link.open();
sql.ExecuteNonQuery();
This results in "Invalid column name abc123.jpg" returned from the try/catch.
Any help would be appreciated. (I wish they would let me do this in PHP lol!)
Thanks,
Tripbrock
You are missing a parenthesis after the column name and the value represents a string and as such must be enclosed in quotes:
string sqlcode = "INSERT INTO file_uploads (upload_filename) " +
"VALUES ('"+filename+"')";
However, the correct way would be to use a parameterized query:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(/*you dont need to see my data here ;)*/);
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
SqlCommand sql = new SqlCommand(sqlcode,link);
sql.Parameters.AddWithValue("#filename", filename);
link.open();
sql.ExecuteNonQuery();
your SQL is bad formatted. Try this :
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Where upload_filename is a name of the column
Really you should be parameterising your queries - this reduces the risk of injection attacks:
string filename = "abc123.jpg";
using( SqlConnection link = new SqlConnection(/*...*/;)) )
{
// sql statement with parameter
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
using( SqlCommand sql = new SqlCommand(sqlcode,link) )
{
// add filename parameter
sql.Parameters.AddWithValue("filename", filename);
link.open();
sql.ExecuteNonQuery();
}
}
Also note the using statements - these make sure that the connection and command objects are disposed of.
Try
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
You were missing a closing parentheses.
Don't know if it is a typo but the line should be:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Notice the ) after upload_filename.
Also also added the single quotes around the filename.
But you probably want to use a parameterized query:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
Then use command.Parameters to add the actual value.
looks like you are missing a bracket:
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
Should be
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Also, to avoid SQL injection attacks you can use the SQLCommand objects like so.
using (SQLCommand oSQLCommand = new SQLCommand("INSERT INTO file_uploads (upload_filename) VALUES ( #FileName )")
{
oSQLCommand.Parameters.AddWithValue("#FileName", filename);
oSQLCommand.ExecuteNonQuery();
}

Categories

Resources