简体   繁体   中英

How to use parameters in SQL query with column name

I have the following SQL query which takes the header from a file and creates a column with the same name as the header:

SqlCommand createtable = new SqlCommand("CREATE TABLE " + tbXLSTableName.Text + " (" + dc.ColumnName + " varchar(MAX))", myConnection);

It is open for an SQL injection attack so I decided to use parameters like this:

string strCreateTable = "CREATE TABLE @TableNameCreateXLS (" + dc.ColumnName + " varchar(MAX))";

SqlCommand createtable = new SqlCommand(strCreateTable, myConnection);      
createtable.Parameters.AddWithValue("TableNameCreateXLS", tbXLSTableName.Text);

dc is a DataColumn object.

I am getting the following error:

Incorrect syntax near @TableNameCreateXLS

How can I resolve the error?

You can't use Parameters for Table Name and Column Names, but you can use SqlCommandBuilder.QuoteIdentifier method to escape their values. Like:

SqlCommandBuilder sqlBuilder = new SqlCommandBuilder();
string columnName = dc.ColumnName;//"somecolumn"
string TableNameCreateXLS = "someTable";
string escapedColumnName = sqlBuilder.QuoteIdentifier(columnName);
string escpaedTableName = sqlBuilder.QuoteIdentifier(TableNameCreateXLS);

string strCreateTable = string.Format("CREATE TABLE {0} ({1} varchar(MAX))",escpaedTableName, escapedColumnName);

Unfortunately, you cannot use parameters for table names. I usually see this being done when people want to query a dynamic table, and in those cases I say the safe thing to do is query the table of table names using a parameter, but in your case it doesn't work.

So aside from sanitizing the table name input yourself, I don't think you have any in-SQL way to do this safely. If creating a table dynamically is unavoidable like this, then at least be sure to sanitize the first.

使用它,看看是否可行:

createtable.Parameters.AddWithValue("@TableNameCreateXLS", tbXLSTableName.Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM