[英]Parameterize ALTER/DROP TABLE OdbcCommand in C#
I am trying to convert the SQL statements in my code from concatenated strings to parameterized queries, but I can not make it work for DROP TABLE
and ALTER TABLE
like these: 我正在尝试将代码中的SQL语句从连接字符串转换为参数化查询,但无法使之适用于
DROP TABLE
和ALTER TABLE
如下所示:
using (OdbcCommand delCmd = new OdbcCommand($"DROP TABLE IF EXISTS ?", dbConnection))
{
delCmd.Parameters.Add(new OdbcParameter("?", OdbcType.NVarChar) { Value = tableName });
delCmd.ExecuteNonQuery();
}
using (OdbcCommand delCmd = new OdbcCommand($"ALTER TABLE ? DROP COLUMN ?", dbConnection))
{
delCmd.Parameters.Add(new OdbcParameter("?", OdbcType.NVarChar) { Value = tableName });
delCmd.Parameters.Add(new OdbcParameter("?", OdbcType.NVarChar) { Value = columnName });
delCmd.ExecuteNonQuery();
}
I have tried adding []
or ''
to either the query string or the parameter, but I never got it to work. 我尝试将
[]
或''
添加到查询字符串或参数中,但是我从未使它起作用。
I get run time error: 我得到运行时错误:
ERROR [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near '@P1'.
错误[42000] [Microsoft] [SQL Server的ODBC驱动程序13] [SQL Server]“ @ P1”附近的语法不正确。 `
`
Any suggestions as to how I can get these queries to work would be a big help! 关于如何使这些查询生效的任何建议将对您大有帮助!
You can't provide table, field names as parameters ; 您不能提供表,字段名称作为参数 ; but you can use formatting or string interpolation :
但是您可以使用格式设置或字符串插值 :
//TODO: validate tableName and columnName here
//since formatting / string interpolation prone to SQL injection
// e.g.
// if (!Regex.IsMatch(tableName, "^[A-Za-z][A-Za-z0-9_]*$")) {/* wrong table */}
using (OdbcCommand delCmd = new OdbcCommand(
$"ALTER TABLE {tableName} DROP COLUMN {columnName}",
dbConnection))
{
delCmd.ExecuteNonQuery();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.