首页 > 解决方案 > C# for Postgres 中的 .CommandText 删除双引号

问题描述

我有一个连接到 Postgres DB 的小型 C# 应用程序。所有表名都以大写字母开头,所以我发现解析表的查询需要有双引号。例如,从“表名”中选择 *。我有这个:

using var cmd = new NpgsqlCommand();
cmd.Connection = npgsqlConnection;
string newstring = " \"x\" ";
string tab = newstring.Replace("x", tableName);
string strSQL = string.Format("select * from {0};", tab);
cmd.CommandText = strSQL; 
Console.WriteLine(strSQL);// I can see the double quotes here
cmd.ExecuteNonQuery();

我从 cmd.ExecuteNonQuery 得到一个异常,因为它找不到表名。我发现 CommandText 中不包含双引号,因此它找不到 TableX,因为它执行 SELECT * FROM TableX 而不是 SELECT * FROM "TableX"。

任何建议都会有所帮助,谢谢。

标签: c#postgresql

解决方案


发现我必须指定架构名称,并且它没有在连接字符串中使用架构名称。架构名称不应包含在双引号中。

这有效:

string newstring = " \"x\" ";
string tab = newstring.Replace("x", tableName);
string strSQL = string.Format("select * from schema.{0};", tab);
cmd.CommandText = strSQL; 

这行不通

string newstring = " \"x\" ";
string tab = newstring.Replace("x", schema.tableName);
string strSQL = string.Format("select * from schema.{0};", tab);
cmd.CommandText = strSQL;

在插入时,列也应该用双引号引起来。


推荐阅读