I am new to Asp.net and I am just starting to work with classes. I recently created a class that will handle most of my SQL queries for me, so I donβt need to repeatedly create new connections across all my files.
One of the methods I created takes an SQL query as a parameter and returns the result. I know that I should use parameterized queries to avoid SQL injections. My question is: how can I do this when I pass the request as a string parameter?
For example, here is the method that I will call:
public static DataTable SqlDataTable(string sql) { using (SqlConnection conn = new SqlConnection(DatabaseConnectionString)) { SqlCommand cmd = new SqlCommand(sql, conn); cmd.Connection.Open(); DataTable TempTable = new DataTable(); TempTable.Load(cmd.ExecuteReader()); return TempTable; } }
So, from another file, I would like to use this method as follows:
DataTable dt = new DataTable(); dt = SqlComm.SqlDataTable("SELECT * FROM Users WHERE UserName='" + login.Text + "' and Password='" + password.Text + "'"); if (dt.Rows.Count > 0) { // do something if the query returns rows }
It works, but will still be vulnerable to injection? Is there a way to pass variables into a string as parameters? I know that I can do this if I create a new SQLCommand object for the query and use Parameters.AddWithValue, but I wanted all my SQL commands to be in a separate class.
source share