C# 在.net中使用SqlCommand使用参数修改数据库
我必须根据一些输入动态修改SQL Server数据库。我想做的是生成修改命令,然后执行它们。为了避免SQL注入,我想使用参数。但它不起作用 以下是我的PoC代码片段(只是一个粗糙的东西): 这会引发语法错误。但这一条有效:C# 在.net中使用SqlCommand使用参数修改数据库,c#,sqlcommand,C#,Sqlcommand,我必须根据一些输入动态修改SQL Server数据库。我想做的是生成修改命令,然后执行它们。为了避免SQL注入,我想使用参数。但它不起作用 以下是我的PoC代码片段(只是一个粗糙的东西): 这会引发语法错误。但这一条有效: public static void ModifyDatabase() { string connectionString = "Server=localhost; Database=DEV_Tests; Integrated
public static void ModifyDatabase()
{
string connectionString = "Server=localhost; Database=DEV_Tests; Integrated Security=True;";
var sqlCommand = "CREATE SCHEMA AAAA";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sqlCommand, connection))
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
所以,或者我做错了什么(可能是),或者我不能在“createschema”中使用参数。事实上,在第二个(没有参数的)中,如果我添加一个参数而不使用它,也会失败。是这样吗?如果我们不能在这里使用params,那么对输入进行清理的最佳方法是什么?修剪它并删除冲突参数
谢谢。您不能在
CREATE
语句中使用参数。相反,请使用QUOTENAME
和sp_executesql
动态执行它:
DECLARE@sqlnvarchar(max)=N'createschema'+QUOTENAME(@SCHEMA);
EXEC sp_executesql@sql;
如果有任何其他参数可以在查询中使用,那么也可以将其传递给sp_executesql
您应该将架构名称作为
nvarchar(128)
传递,这与sysname
相同:
command.Parameters.Add(“@schemaname”,SqlDbType.NVarChar,128)。Value=name;
另一个小技巧:为了避免养成连接/注入SQL的习惯,我总是将我的查询变量声明为conststringquery
public static void ModifyDatabase()
{
string connectionString = "Server=localhost; Database=DEV_Tests; Integrated Security=True;";
var sqlCommand = "CREATE SCHEMA AAAA";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sqlCommand, connection))
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}