我正在尝试使用Npgsql
和command.Parameters.AddWithValue
函数创建表格。以下是代码:
尝试1:
string databaseName = "MyDatabase";
using (NpgsqlCommand command = new NpgsqlCommand(" CREATE DATABASE :DBNAME ", conn))
{
command.Parameters.AddWithValue(":DBNAME", "'" + databaseName + "'");
await command.ExecuteNonQueryAsync();
}
尝试2:
string databaseName = "MyDatabase";
using (NpgsqlCommand command = new NpgsqlCommand(" CREATE DATABASE :DBNAME ", conn))
{
command.Parameters.AddWithValue(":DBNAME", "\"" + databaseName + "\"");
await command.ExecuteNonQueryAsync();
}
尝试3
string databaseName = "MyDatabase";
using (NpgsqlCommand command = new NpgsqlCommand(" CREATE DATABASE :DBNAME ", conn))
{
command.Parameters.AddWithValue(":DBNAME", databaseName);
await command.ExecuteNonQueryAsync();
}
由于syntax error at or near "$1"
错误,我无法执行此代码。我究竟做错了什么?我已经将这种语法用于选择查询,并且没有问题,例如:
using (NpgsqlCommand command = new NpgsqlCommand(" SELECT * FROM \"Students\" WHERE \"Id\" = :Id ", conn))
{
command.Parameters.AddWithValue(":Id", 1);
int id = (int)await command.ExecuteScalarAsync();
}
这个查询完美无缺。有什么区别?
编辑:如何创建阻止SQL注入的数据库和表?以下声明安全吗? format('CREATE DATABASE %1$s', 'MyDatabase')