Paramaterized Query With SQL Data Reader C# - c#

I know that non parameterized queries are frowned upon because of SQL injection. Well, I have a lot of queries in my application that are susceptible to SQL injection. I just can't seem to wrap my head around doing it with SqlDataReader. I am able to do it with ExecuteNonQuery just not SQLDataReader.
Can someone give me some pointers and or examples of the best way to do this, the query is executing and returning exactly what it should, I just want to make it as secure as possible....
Code:
string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
+ "WHERE [customerName] = '" + customer + "' AND " + "[customerPin] = '" + customerID + "'";
sqlCmd = new SqlCommand(myQuery, conn);
sqlCmd.Connection.Open();
SqlDataReader rdr2 = sqlCmd.ExecuteReader();
if (rdr2.HasRows)
{
rdr2.Read();
shoeSize= rdr2["Shoe Size"].ToString();
shoeBrand= rdr2["Shoe Brand"].ToString();
}
conn.close();

There you go
string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
+ "WHERE [customerName] = #customerName AND [customerPin] = #customerID"
sqlCmd = new SqlCommand(myQuery, conn);
sqlCmd.Connection.Open();
sqlCmd.Parameters.AddWithValue("#customerName", customerName);
sqlCmd.Parameters.AddWithValue("#customerID", customerID");
--rest stays the same as before
Whereas #customerName and #customerID are now your parameters. So even if the customer's name should be something like "Bigler, Fabian' DROP TABLE [myTable]" it will not work. It completely removes the possibility of "evil" input changing the meaning of your query.
Non-parameterized queries are not simply 'frowned upon'. It can be disastrous for you, your company and - of course - your customer.

Like this:
string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
+ "WHERE [customerName] = #customerName AND [customerPin] = #customerPin";
sqlCmd = new SqlCommand(myQuery, conn);
sqlCmd.Connection.Open();
sqlCmd.Parameters.Add("#customerName", SqlDbType.NVarChar, 50).Value = customer;
sqlCmd.Parameters.Add("#customerPin", SqlDbType.NVarChar, 20).Value = customerID;
SqlDataReader rdr2 = sqlCmd.ExecuteReader();
if (rdr2.HasRows)
{
rdr2.Read();
shoeSize = rdr2["Shoe Size"].ToString();
shoeBrand = rdr2["Shoe Brand"].ToString();
}
conn.close();

Related

MySqlDataReader Hasn't Row But Query has data

My Query in PHPmyadmin has result but in C#, a.read() returns no data.
string query = "SELECT answer FROM tbl WHERE level = " + level + " AND subject = '" + subject[i] + "';";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader a = command.ExecuteReader();
while (a.Read())
{
//Do Some Things
}
connection.Close();
Edit:
I've already tried parameterized queries, didn't work, and also tried with the constant values from the table, it doesn't work in the project, but when I run the query in the database it works

ExecuteScalar() always returns NULL even though there is data in the database

I am trying to make a simple memory game on visual Studio using C#. This game must keep some user records in the database. My database is not empty. This is part of my code :
string ConnectionString = #"Data Source =" + Application.StartupPath + #"\mydb.sdf";
SqlCeConnection sqlConnection1 = new SqlCeConnection(#"Data Source=" +Application.StartupPath + #"\mydb.sdf");
System.Data.SqlServerCe.SqlCeCommand cmdt = new System.Data.SqlServerCe.SqlCeCommand(ConnectionString);
cmdt.CommandText = "insert into logs (Sessionid, score, Minutes, Hintcount, Errorcount, Level, Picname) values(#ID, #Score, #Minutes, #Hintcount, #Errorcount, 'Level 1', #Picname)";
cmdt.Connection = sqlConnection1;
sqlConnection1.Open();
{
SqlCeCommand cmd = new SqlCeCommand("select ID from Userrecords where ID=(select MAX(ID) from Userrecords) and Username='" + LoginInfo.UserID + "'", sqlConnection1);
cmd.UpdatedRowSource = UpdateRowSource.OutputParameters;
int id = (int)cmd.ExecuteScalar();
cmdt.Parameters.AddWithValue("#Score", point);
cmdt.Parameters.AddWithValue("#Minutes", time);
cmdt.Parameters.AddWithValue("#Hintcount", hbuttoncount);
cmdt.Parameters.AddWithValue("#Errorcount", errorcount);
cmdt.Parameters.AddWithValue("#Picname", nameused2);
cmdt.Parameters.AddWithValue("#ID", id);
cmdt.UpdatedRowSource = UpdateRowSource.OutputParameters;
cmdt.ExecuteNonQuery();
sqlConnection1.Close();
}
I am trying to use executeScalar method, in order to retrieve the session ID from another table. But it always returns NULL, so it throws an exception. Is there any alternative that i can use?
I think you want the latest ID for this Username, then your query is wrong. Use:
var sql = #"SELECT MAX(ID) As Id
FROM Userrecords
WHERE Username = #UserName";
SqlCeCommand cmd = new SqlCeCommand(sql, sqlConnection1);
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = LoginInfo.UserID;
Your query returned the max-id if this record accidentially had the searched Username.

Prevent sql injection by removing characters and other possible ways

SQL injection can be avoided if I remove "'" character in the variables of a sql query. The sql query that I use is:
dbCommand = new OleDbCommand("update Table1 set PhoneNo = '" + phone + "' where Table1.Company = '" + company + "'", dbConnection);
dbCommand.ExecuteNonQuery();
I also use SELECT sql query in a similar way:
dbReader = new OleDbCommand("select * from Table1 where Table1.Company = '" + company + "'", dbConnection).ExecuteReader();
dbReader.Read();
if (dbReader.HasRows)
{
//Do operations using dbReader["Company"]
}
Are there any other characters in the variables that can cause SQL injection or other risks? I can remove those. What are other ways of preventing SQL injection or other risks?
The best way is simply to use parametrized queries and don't try and remove any '. One example would be this:
dbCommand = new OleDbCommand("update Table1 set PhoneNo = ? where Table1.Company =? ", dbConnection);
dbCommand.Parameters.Add(phone);
dbCommand.Parameters.Add(company);
The OleDbCommand class allows you to specify parameters by name also, according to MSDN.
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparametercollection.aspx
So you could replace those ? in my example, with actual parameter names like so:
dbCommand = new OleDbCommand("update Table1 set PhoneNo = #phone where Table1.Company =#company ", dbConnection);
dbCommand.Parameters.Add("#phone",phone);
dbCommand.Parameters.Add("#company",company);
Update (Comment from Steve)
You could use a name for the parameter, but it is ignored by OleDb. If
you change the order in which you add the parameter the query doesn't
work – Steve
Try to change it to this
dbCommand = new OleDbCommand("update Table1 set PhoneNo = #PhoneNo where Table1.Company = #company ", dbConnection);
dbCommand.Parameters.Add("#PhoneNo", phone );
dbCommand.Parameters.Add("#company", company );

How to make a filtration by a parameter in CommandText in C#?

I would like to fill a ComboBox but I want to sort data by one parameter called “id_group”.
I wrote a code but it does not work.
In this line happens an exception which says “incorrect syntax” :
SqlDataReader sd = sc.ExecuteReader();
This is all my code:
int id_group=5;
SqlConnection conn = new SqlConnection();
SqlCommand sc = conn.CreateCommand();
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP '" + id_group + "'";
conn.Open();
SqlDataReader sd = sc.ExecuteReader(); //this happens exception - "incorrect syntax"
while (sd.Read())
{
string graduate = (string)sd["STUDENT"];
Student_comboBox.Items.Add(graduate);
}
conn.Close();
How to make it work?
Is there other ways to filter data by a parameter?
actually you are missing = on your query, so this should looked like this,
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = '" +
id_group + "'";
but please do parameterize it to avoid SQL Injection
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = #groupID";
sc.Parameters.AddWithValue("#groupID", id_group);
SOURCE
AddWithValue
Add (recommended to use)

C#, trouble with SQLreader/command

I have some trouble with the SqlDataReader:
public string GetVareNavn(string streg)
{
string navn = "";
SqlConnection myCon = DBcon.getInstance().conn();
string query =
"SELECT Navn FROM Vare WHERE Stregkode = ) Values('" + streg + "')";
myCon.Open();
SqlCommand com = new SqlCommand(query, myCon);
Console.WriteLine("navn: "+navn);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
navn = dr.GetString(1);
}
myCon.Close();
return navn;
}
It throws an exception at com.ExecutiveReader(); and the exception is:
Incorrect syntax near ')'.
I don't know why this one doesn't work right now, because I've used it in another project.
Your query looks like it was copied from something that used to be an INSERT statement; you don't need the VALUES... clause at the end of the statement. Try changing your query to:
string query =
"SELECT Navn FROM Vare WHERE Stregkode = #streg";
Then modify this code to use the parameter:
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.AddWithValue("#streg", streg);
It doesn't work because your SQL is broken:
SELECT Navn FROM Vare WHERE Stregkode = ) Values('" + streg + "')"
What did you expect that WHERE clause to do, and what values are you trying to use? It looks like you've got a broken copy/paste from an update command.
Additionally, you shouldn't put values into your SQL like that anyway - you should use parameterized queries to avoid SQL injection attacks (and to avoid formatting issues etc).
Ya, surely it will give. Why you put the Values in your select query? which is wrong syntax, Try Now.
string query = "SELECT Navn FROM Vare WHERE Stregkode = '" + streg + "'";

Categories