PostgreSQL、Npgsql 返回 42601:“$1”处或附近的语法错误
PostgreSQL, Npgsql returning 42601: syntax error at or near “$1”
传递 PostgreSQL 命令时出现以下错误
42601: syntax error at or near ""
using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(DBManager.GetConnectionString()))
{
conn.Open();
Logger.Info("connection opened for adding column");
using (Npgsql.NpgsqlCommand addColumnQuery = new Npgsql.NpgsqlCommand(@"ALTER TABLE @tableName ADD COLUMN IF NOT EXISTS @columnName @columnType;", conn))
{
addColumnQuery.Parameters.AddWithValue("@tableName", tableName);
addColumnQuery.Parameters.AddWithValue("@columnName", columnName);
addColumnQuery.Parameters.AddWithValue("@columnType", columnType);
addColumnQuery.ExecuteNonQuery();
}
}
经过一些测试,我发现只有 table 值可以作为参数传递,而不是 table 名称和列名。所以我像这样更改了代码
ALTER TABLE tableName ADD COLUMN columnName columnType;
传递 PostgreSQL 命令时出现以下错误
42601: syntax error at or near ""
using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(DBManager.GetConnectionString()))
{
conn.Open();
Logger.Info("connection opened for adding column");
using (Npgsql.NpgsqlCommand addColumnQuery = new Npgsql.NpgsqlCommand(@"ALTER TABLE @tableName ADD COLUMN IF NOT EXISTS @columnName @columnType;", conn))
{
addColumnQuery.Parameters.AddWithValue("@tableName", tableName);
addColumnQuery.Parameters.AddWithValue("@columnName", columnName);
addColumnQuery.Parameters.AddWithValue("@columnType", columnType);
addColumnQuery.ExecuteNonQuery();
}
}
经过一些测试,我发现只有 table 值可以作为参数传递,而不是 table 名称和列名。所以我像这样更改了代码
ALTER TABLE tableName ADD COLUMN columnName columnType;