ADO.NET SQL Server and parameterized queries


Never build your SQL by concatenating an long SQL command stirng is a good practice considering SQL injection risks. I admit I sometimes "cheats" - I mean say this example



public DataSet GetCats(long lId2)
{
string sSQL = "select * from categories where id2=" + lId2.ToString();
return ExecuteSQL(sSQL);
}


This example would NOT be open for injection attacks (it mostly involves strings) , cause .NET typesafety ensures that GetCats function is never called with something else than a long.

However take my advise and NEVER build the SQL command - here's how to do it:



            System.Data.SqlClient.SqlParameter[] oParamColl = new System.Data.SqlClient.SqlParameter[2];
            oParamColl[0] = new System.Data.SqlClient.SqlParameter("@catid", SqlDbType.Int);
            oParamColl[0].Value = 7;
            oParamColl[1] = new System.Data.SqlClient.SqlParameter("@catid2", SqlDbType.Int);
            oParamColl[1].Value = 3;
            DataSet dd = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(sConn,
                CommandType.Text, sSQL, oParamColl);
            dataGridView1.DataSource = dd.Tables[0];


I mean, if you are using some sort of codegeneration tool - you will not have to handwrite that code anyway.

(I will try to publish some basic type of codegenerator for you all which works with SQL Server stored procedures)