I\'m using C# and .NET 3.5. I need to generate and store some T-SQL insert statements which will be executed later on a remote server.
For example, I have an array o
Use parameterised commands. Pass the parameters along to your remote server as well, and get that to call into SQL Server, still maintaining the distinction between the SQL itself and the parameter values.
As long as you never mix treat data as code, you should be okay.
To avoid injection, you need to ship the data to the remote server (perhaps in XML) and then on the remote server, the data should be converted back to appropriate data types and used in parameterized queries or stored procs.
Create your SqlCommand object like so:
SqlCommand cmd = new SqlCommand(
"INSERT INTO Employees (id, name) VALUES (@id, @name)", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.Value = employee.ID;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@name";
param.Value = employee.Name;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
Hmm I agree with everyone else that you should be using parameterized queries and will leave it at that. But how are you going pass these sql statements to your remote server? Do you have some type of service like a web service which will accept and execute arbitrary Sql commands or is your client app going to hit the DB directly?
If your going through some sort of proxy then no matter how much you sanitize your data on the client, a hacker could just bypass your app and hit the service. In which case do what Cade recommends and pass the data as XML for example or whatever format you choose (JSON, Binary etc..) Then build your SQL right before you actually run the command.
Fix your replace quotes function this way:
void string replaceQuotes(string value) {
string tmp = value;
tmp = tmp.Replace("'", "''");
return tmp;
}
Cheers!