-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathSqlInjection.cs
More file actions
48 lines (44 loc) · 1.76 KB
/
SqlInjection.cs
File metadata and controls
48 lines (44 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
class SqlInjection
{
TextBox categoryTextBox;
string connectionString;
public DataSet GetDataSetByCategory()
{
// BAD: the category might have SQL special characters in it
using (var connection = new SqlConnection(connectionString))
{
var query1 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='"
+ categoryTextBox.Text + "' ORDER BY PRICE";
var adapter = new SqlDataAdapter(query1, connection);
var result = new DataSet();
adapter.Fill(result);
return result;
}
// GOOD: use parameters with stored procedures
using (var connection = new SqlConnection(connectionString))
{
var adapter = new SqlDataAdapter("ItemsStoredProcedure", connection);
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
var parameter = new SqlParameter("category", categoryTextBox.Text);
adapter.SelectCommand.Parameters.Add(parameter);
var result = new DataSet();
adapter.Fill(result);
return result;
}
// GOOD: use parameters with dynamic SQL
using (var connection = new SqlConnection(connectionString))
{
var query2 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY="
+ "@category ORDER BY PRICE";
var adapter = new SqlDataAdapter(query2, connection);
var parameter = new SqlParameter("category", categoryTextBox.Text);
adapter.SelectCommand.Parameters.Add(parameter);
var result = new DataSet();
adapter.Fill(result);
return result;
}
}
}