Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# prevent SQL injection for create statement

Does it make sense to prevent sql injection for a create statement? How could I do this? I wanted to use command parameters, but it doesn't seam to work:

Example:

var createSql = "CREATE TABLE @TableName (@Column1 ...)";
var command = new SqlCommand();

command.CommandText = createSql;
command.Parameters.AddWithValue("@TableName", "XYZ");
command.Parameters.AddWithValue("@Column1", "Col");

// somewhere else
command.Connection = connection;
command.ExecuteNonReader(); // --> exception: invalid syntax at @TableName

Edit: The Column and TableNames are generated depending on other data. Indirectly also on userinput, yes. The given create statement is incomplete. It is just an example.

My problem is, that it seems that the command parameters are not replaced.

like image 713
Daniel Bişar Avatar asked Mar 02 '26 23:03

Daniel Bişar


1 Answers

You cannot use bind variables for table or column names.

So you'll have to construct that SQL statement using string concatenation and if necessary, manual quoting/escaping, and be very careful how you go about it.

Direct user input would be very dangerous, but if it is only indirectly, for example just choosing options for auto-generated names, you should be okay.

like image 72
Thilo Avatar answered Mar 05 '26 13:03

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!