title: parameterized queries vs. SQL injection
body: <p>I am new to Asp.net and I'm just starting to work with classes.  I recently created a class that will handle most of my SQL queries for me so that I don't have to repeatedly create new connections over all my files.</p>
  
  <p>One of the methods I've created takes in an SQL query as a parameter and returns the result.  I know that I should be using parameterized queries to avoid SQL injections.  My question is, how can I do this when I'm passing the query as a string parameter?</p>
  
  <p>For example, here's a method I'll be calling:</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>So from another file I'd like to use this method like so:</p>
  
  <pre><code>DataTable dt = new DataTable();
  
  dt = SqlComm.SqlDataTable("SELECT * FROM Users WHERE UserName='" + login.Text  + "' and Password='" + password.Text + "'");
  
  if (dt.Rows.Count &gt; 0)
  {
     // do something if the query returns rows
  }
  </code></pre>
  
  <p>This works but would still be vulnerable to injections right?  Is there a way I can pass the variables to the string as parameters?  I know 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 the separate class.</p>