Prevent sql injection by removing characters and other possible ways - c#

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 );

Related

Display data in 2 tables in one crytal report in c#

I am trying to display some data on crystal report. after written the code the issued part of the report displayed well while the receiving part displayed only the first data within the range selected and duplicated several times. here is the code below
public DataSet itembincardreport(string date1, string date2, string
itemcode)
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = null;
Connection cs = new Connection();
con = new SqlConnection(cs.DBcon);
con.Open();
DataSet ds = new DataSet();
frmReport frm = new frmReport();
string sql = "select * from ISSUED, RECEIVED WHERE
ISSUED.ITEMCODE=RECEIVED.ITEMCODE AND ISSUED.ITEMCODE = '" + itemcode + "'
AND RECEIVED.ITEMCODE = '" + itemcode + "' and ISSUED.TRANSDATE
between '" + Convert.ToDateTime(date1) + "' and '" +
Convert.ToDateTime(date2) + "' and RECEIVED.TRANSDATE between '" +
Convert.ToDateTime(date1) + "' and '" + Convert.ToDateTime(date2) + "'";
SqlDataAdapter dadbt = new SqlDataAdapter(sql, mycon.DBcon);
dadbt.Fill(ds);
dadbt.Dispose();
return ds;
}
The root cause of your problem is the query. Whether the received and issued tables have multiple rows that match each other or not, I cannot say (you need to post some better example table data than the screenshot given) but your query in the string should be written like this:
string sql =
#"select *
from
ISSUED
inner join
RECEIVED
on
ISSUED.ITEMCODE=RECEIVED.ITEMCODE -- this is probably the fault
-- try joining on ISSUEDID = RECEIVED instead??
where
ISSUED.ITEMCODE = #itemcode and
ISSUED.TRANSDATE between #date1 and #date2 and
RECEIVED.TRANSDATE between #date1 and #date2";
Later in your code, you should call:
var c = new SqlCommand();
c.CommandText = sql;
c.Connection mycon;
c.Parameters.AddWithValue("#itemcode", itemcode);
c.Parameters.AddWithValue("#date1", Convert.ToDateTime(date1)); //you should make the method argument a DateTime
c.Parameters.AddWithValue("#date2", Convert.ToDateTime(date2)); //you should make the method argument a DateTime
SqlDataAdapter dadbt = new SqlDataAdapter(c);
That's how to PROPERLY do database queries with parameters.. Now whether there are duplicate rows or not is purely down to your table data*, but at least your SQL is immune from hackers putting an itemcode of '; DROP table issued; -- in and screwing up your world
*post some detailed example data if you want help with that and I'll edit this answer. Take a look at SQLFiddle.com

Paramaterized Query With SQL Data Reader 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();

SQL Query Problems with Tables

public void SPROC_LoadGroups()
{
//This gets the table name.
string tablename = cboNetChannel.SelectedItem.ToString();
SqlConnection sqlConnectionCmdString = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Rick\Documents\Visual Studio 2010\Projects\Server\database\ClientRegit.mdf;Integrated Security=True;User Instance=True");
//This is the table name and Query that identifies with the selected table
string Command = "SELECT Client_Groups" + "FROM" + tablename;
SqlCommand sqlCommand = new SqlCommand(Command, sqlConnectionCmdString);
SqlDataAdapter objDA = new SqlDataAdapter(sqlCommand);
DataSet dsGroups = new DataSet();
objDA.Fill(dsGroups, "dtGroup");
cboExistingG.DataSource = dsGroups.Tables["dtGroup"];
cboExistingG.DisplayMember = "Client_Groups";
//cboExistingG.ValueMember = "ID";
}
Error I am getting is this {"Incorrect syntax near '-'."}
I got a situation is it possible to query as table with a name similar to a GUID value
my table name is 43d5377-0dcd-40e6-b95c-8ee980b1e248
I am generating groups that are identified with a Networking Data table that is named 43d5377-0dcd-40e6-b95c-8ee980b1e248 The table name is allowed and SQL does not prohibit such table names.
This is my code I am getting an error, I am table mapping with this by creating a Query that allows me to identify the query with the selected table value.
If your table name is similar as a GUID add [] block
something like:
string Command = "SELECT Client_Groups FROM [" + tablename+ "]";
Best Regards
You were missing a space between the concatination of these two strings:
"SELECT Client_Groups" + "FROM"
change to
"SELECT Client_Groups " + "FROM "
SqlCommand cmd;
cmd = new SqlCommand("SELECT client_Groups FROM Table name where name='" + txtbox. Text + "' , lastname='" + txtbox. Text + "'", con);

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