Use parameter based queries instead of trying to sanitize strings – its much safer and easier.

Good resources:

http://stackoverflow.com/questions/249567/algorithm-to-avoid-sql-injection-on-mssql-server-from-c-sharp-code

C++ .Net example of a parameter based query


	SqlConnection1->Open();
	SqlClient::SqlDataAdapter ^SqlDataAdaptor1 = gcnew SqlClient::SqlDataAdapter();
	SqlDataAdaptor1->MissingSchemaAction = MissingSchemaAction::AddWithKey;
	DataSet ^DataSet1 = gcnew DataSet();
	SqlClient::SqlCommand ^SqlCommand1 = gcnew SqlClient::SqlCommand();
	SqlCommand1->Connection = SqlConnection1;
	SqlClient::SqlCommandBuilder ^CmdBuilder1 = gcnew SqlClient::SqlCommandBuilder();
	CmdBuilder1->DataAdapter = SqlDataAdaptor1;

	//----- GET TABLE -----
	SqlCommand1->CommandText = "SELECT * FROM MyTable WHERE MyColumnName = @Param1";
	SqlCommand1->Parameters->AddWithValue("@Param1", SomeVariableValue);

	SqlDataAdaptor1->SelectCommand = SqlCommand1;
	SqlDataAdaptor1->Fill(DataSet1, "MyTable");
	DataTable ^Table1 = DataSet1->Tables["MyTable"];

	//----- READ ROWS -----
	if (Table1->Rows->Count)
These are the important lines:

	SqlCommand1->CommandText = "SELECT * FROM MyTable WHERE MyColumnName = @Param1";
	SqlCommand1->Parameters->AddWithValue("@Param1", SomeVariableValue);

There is no need to add single quotes around string etc parameters in the Command Text, this is fine:


	SqlCommand1->CommandText = "SELECT * FROM MyTable WHERE MyColumnName = @Param1";
	SqlCommand1->Parameters->AddWithValue("@Param1", SomeString);

 

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published.