SQL Syntax in C# - c#

I'm trying to understand why in C# if you have a sql string why you would have to put tick (') marks in the following where clause in order for this to work. Could someone please explain the reasoning behind this?
where ProgramServer='" + machineName.ToString() + "' and Active=1;

You can avoid those tick (') marks and use Parameters, They will also save you from SQL Injection.
The reason you see those ticks are because SQL expects string type values to be enclosed in single ticks.

What you're seeing is a dynamically built SQL query in the code. When querying based on a string value, the string must be wrapped in single quotes. The final SQL string would look something like:
select * from someTable where ProgramServer = 'YourMachineName' and Active = 1;
Unfortunately, that is far from the best way to do things. You should be using parameterized queries instead:
var query = "select * from someTable where ProgramServer = #machineName and Active = 1;";
using(var conn = new SqlConnection(connString))
{
var command = new SqlCommand(query, conn);
command.Parameters.Add("machineName", machineName.ToString());
// Execute and get the results
}

Related

Invalid Column Name: "value" - Error Even though it works in another form.

I am stuck at one problem and I just can't solve this.
I get this Error:
Error Message
That's the relevant table
The Code:
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = "UPDATE CAC SET nextMaintainance = #nextMaintainance WHERE department = " + #departmentCB.Text;
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#nextMaintainance", nextMaintainanceDT.Value);
command.ExecuteNonQuery();
The weird thing I don't understand is that a similar code works just fine without any error in my project:
query = "UPDATE LDV SET received = #received, department = #department WHERE Id =" + #idTxt.Text;
command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#received", inDT.Value);
command.Parameters.AddWithValue("#department", departmentCb.Text);
command.ExecuteNonQuery();
MessageBox.Show("Lungenautomat wurde aktualisiert");
If relevant, my connection string:
connectionString = ConfigurationManager.ConnectionStrings["SCBA_Manager_0._1.Properties.Settings.SCBAmanagerConnectionString"].ConnectionString;
I really hope you can help me :(
Thank you!
The department column is a text column, so comparing it to a value means the value should be wrapped in quotes.
// This fix is not the recommended approach, see the explanation after this code block
string query = "UPDATE CAC SET nextMaintainance = #nextMaintainance WHERE department = '" + departmentCB.Text + "'";
// ^--------------------------^------ single quote added to wrap the value returned by departmentCB.Text
On the other hand, this error does not occur in your second example, because there you're correctly using the Parameters.AddWithValue() method to add the value for the #department parameter, and because id is a numeric column, so it doesn't require the value wrapped in quotes.
However, while the code shown above does the job, it is not the right way of doing the job. The correct way is to used parameters for all values to be injected into a query. The queries you've shown above are already correctly using parameters for some values (e.g. nextMaintenance in the first query, received and department in the second), but are incorrectly doing string concatenation for other values (e.g. department in the first query, id in the second).
Usage of Parameterized SQL
The benefit of using parameterized SQL is that it automatically takes care of adding quotes, prevents SQL injection, etc.
Therefore, its best to change your first code block to:
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = "UPDATE CAC SET nextMaintainance = #nextMaintainance WHERE department = #department";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#department", departmentCb.Text);
command.Parameters.AddWithValue("#nextMaintainance", nextMaintainanceDT.Value);
command.ExecuteNonQuery();
Notice how the string query is a single string without any messy concatenation, and that it contains two parameters #nextMaintenance and #department? And how the values for those parameters are correctly injected using Parameters.AddWithValue() in the following lines?
Your second code block can be similarly improved by using a parameter for the Id column.
query = "UPDATE LDV SET received = #received, department = #department WHERE Id = #Id ";
command.Parameters.AddWithValue("#Id", idTxt.Text);
Further Information
Do read up about SQL injection ( https://technet.microsoft.com/en-us/library/ms161953(v=sql.105).aspx ) to see how using string concatenation like your original code can lead to various security issues, and why parameterized queries are the preferred way of injecting dynamic values into SQL queries.
You can read up more about parameterized queries here: https://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx
In your first example, the WHERE clause evaluates to
WHERE department = Kasseedorf
wheras it should be
WHERE department = 'Kasseedorf'
So the line should be
string query = "UPDATE CAC SET nextMaintainance = #nextMaintainance WHERE department = '" + #departmentCB.Text +"'";
It works in the second example, because id is an integer and doesn't neet quotes.

select query does not work with parameters using Parameters.AddWithValue

The following query in C# doesn't work, but I can't see the problem:
string Getquery = "select * from user_tbl where emp_id=#emp_id and birthdate=#birthdate";
cmdR.Parameters.AddWithValue("#emp_id", userValidate.emp_id);
cmdR.Parameters.AddWithValue("#birthdate", userValidate.birthdate);
OdbcCommand cmdR = new OdbcCommand(Getquery, conn);
OdbcDataReader Reader = cmdR.ExecuteReader();
Reader.HasRows returns no result but when I query it to my database I got data.
I'll assume your code is actually not quite as presented, given that it wouldn't currently compile - you're using cmdR before you declare it.
First, you're trying to use named parameters, and according to the documentation of OdbcCommand.Parameters, that isn't supported:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder.
Additionally, I would personally avoid using AddWithValue anyway - I would use something like:
string sql = "select * from user_tbl where emp_id = ? and birthdate = ?";
using (var connection = new OdbcConnection(...))
{
connection.Open();
using (var command = new OdbcCommand(sql, connection))
{
command.Parameters.Add("#emp_id", OdbcType.Int).Value = userValidate.EmployeeId;
command.Parameters.Add("#birthdate", OdbcType.Date).Value = userValidate.BirthDate;
using (var reader = command.ExecuteReader())
{
// Use the reader here
}
}
}
This example uses names following .NET naming conventions, and demonstrates properly disposing of resources... as well as fixing the parameter issue.
I do think it's slightly unfortunate that you have to provide a name for the parameter when adding it to the command even though you can't use it in the query, but such is life.
Use like this:
string Getquery = "select * from user_tbl where emp_id=? and birthdate=?";
cmdR.Parameters.AddWithValue("#emp_id", userValidate.emp_id);
cmdR.Parameters.AddWithValue("#birthdate", userValidate.birthdate);
OdbcCommand cmdR = new OdbcCommand(Getquery, conn);
OdbcDataReader Reader = cmdR.ExecuteReader();
while(Reader.Read())
{
//Do something;
}
I know this thread is old, but I wanted to share my solution for anyone else coming up on this.
I was having issues with the typical method that Jon posted. I have used it before, but for some reason with this new string I had it was not wanting to actually place the parameter correctly and was causing the reader to not work.
I ended up doing something like this instead, since in the end we are just replacing parts of a string.
string sql = "select * from user_tbl where emp_id = "+ var1 +" and birthdate = "+
var2""
OdbcCommand command = new OdbcCommand(sql);
This was easier for me to get to work. Be warned though, I am not sure if it has any specific drawbacks when compare to using the command parameter method.

Properly check if a record already exists in a database

I have read other questions on this, but it does not help for the most part.
Trying to check if a file has already been uploaded(filename is sent to this table) before creating another record and allowing them to upload the same file again.
I am using this code and it keeps telling me every file is a new file, even when I use the same file for testing. Obviously it should result in "Exists". Connection is already established using "this.Master.Conn" so please no SQLCommand stuff.
I even tried using wildcards in the query.
private string SQLCheck(string FileName)
{
string Check = "Select VideoURL from TrainingVideo2 where VideoURL Like '" + FileName +"' and Status=1;";
Object ob = this.Master.Conn.ExecuteSqlScalarCommand(Check);
string Result;
if (DBNull.Value.Equals(ob))
{
Result = "Exists";
}
else
{
Result = "NewFile";
}
return Result;
}
Also, does anybody have a better(more efficient) way of doing this?
Trying to basically rewrite this in c#.
Private Function CheckName(name As String) As Int32
Dim sql As String = "SELECT ID FROM Company Where Name Like '" & name & "' "
Dim ob As Object = Conn.ExecuteSqlScalarCommand(sql)
If IsDBNull(ob) Then
Return 0
Else
Return CInt(ob)
End If
End Function
There are new and more innovative methods devised to get around the simple "replace all ` and " characters with ..." SQL injection prevention techniques. In your case, if the VideoURL happens to be a varchar (and not nvarchar), then using unicode character U+02BC (URL encoded = %CA%BC) would pass in a quote character as a unicode string, which would bypass your C# checks, but SQL Server will conveniently convert to a quote character in your query. This is just one example of why you should not be doing this :).
In terms of you check, I always prefer using TOP 1 to let SQL Server cut a potential table scan short. So, I would use this query:
Select TOP 1 SomeNonNullIntColumn from TrainingVideo2 where VideoURL Like ... and Status=1;
Execute the query with ExecuteScalar. If the result is null, then the record does not exist.
Never build up an SQL string like that. See SQL injection.
Why are you using like? Do you really have Sql wildcards in that fileName?
Example (sorry for the "SqlCommand stuff", but it's important):
string sql = "select count(*) from TrainingVideo2 where VideoURL = #Name and Status=1"
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", fileName);
conn.Open();
return (Int32)cmd.ExecuteScalar() > 0;
}

C# SQL string formatting

I am new to .net/C#. Coming from PHP and some Java, I am finding the new languages interesting and challenging.
I have an issue with a sql string
string query = #"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = '"+querystring + "' ORDER BY lname ASC";
Which to me, looks fine. however when run my solution and output the query as it is not working, I get this as my output:
select * from Users where role='member' and SUBSTRinG(lname, 1, 1)
= ' O ' ORDER BY lname ASC
This is output into my Firebug console (the page that uses this query is accessed via AJAX).
Is their a reason my 's are being turned into their code version, ie '&#39'
Thanks
In C# you should be using SqlCommand to excute the query, and to prevent sql injection using the parameter collection.
Your query seems fine - The issue might be the way you are running it or the parameters being supplied. Update your question with more details on what you are expecting vs what is happening, include any error messages generated.
Below is a general guideline of how to get data from a sql table to a c# Data Table object.
SqlConnection conn = new SqlConnection("YourConnectionString");
SqlCommand cmd = new SqlCommand(#"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = #query ORDER BY lname ASC");
cmd.Parameters.AddWithValue("#query", querystring);
DataTable resultTable = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(resultTable);
} finally {
if (conn.State != ConnectionState.Closed) conn.Close();
}
Console.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));
For SQL injection protection:
You can provide escape sequence for single quotes by replacing them with two single quotes '' so that it will be treated as a single quote inside SQL strings. Otherwise it is considered as a start or end of the string value in SQL.
Replacing single quotes using ' in .net is also preferred but its better going with two single quotes.

What does "WHERE x = ?" mean in SQL

This code is written in C# and it is calling database to get the data from it. But I don't understand what does "WHERE b.CompRec = ?" mean
public string GetFileNameAndTitle(int compRec)
{
string fileNameAndTitle = "";
string sql = "SELECT a.FileName, a.Title FROM (Files a INNER JOIN Components b ON a.RecNo=b.FileRec) WHERE b.CompRec = ?";
using (OleDbCommand cmd = new OleDbCommand(sql, cn))
{
cmd.Parameters.AddWithValue("#CompRec", compRec);
OpenConnection(); }
It is a parameterized statement.
cmd.Parameters.AddWithValue("#CompRec", compRec);
That line sets the actual value when the query is executed at the server. This prevents SQL Injection and is the 100% right approach!
It's basically a placeholder where you will put data later. This lets you split up your SQL statement from the data used in the query. This is the syntax of parameterized statements.

Categories

Resources