3

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.

1
  • Where are the column and table names coming from? User input? Commented Aug 21, 2013 at 9:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

in this specific code there can't be sql injection because the user doesn't have a say in this.

sql injection are caused when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed

in your case the user doesn't input anything so there is no worry.

however, your create table query is invalid. you can read here on create statement.

you can't use the "..." in a create statement, and every column must have a type

1 Comment

@SACO judging by the edit, you need to replace the headline because this is not an sql injection question, it's a SqlCommand parameters question, and also you should give us the real code with the full exception thrown, cus' right now all i can do i direct you to information and examples on SqlCommand parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.