C# 中的 SQL 插入命令

本文关键字:命令 插入 SQL 中的 | 更新日期: 2023-09-27 18:35:29

我目前正在创建一个小型C#程序,该程序将文件中的数据插入到postgres表中。

执行插入的代码如下所示:

 NpgsqlCommand cmd = new NpgsqlCommand(@"INSERT INTO :table(text) VALUES (:word);", con);
 cmd.Parameters.AddWithValue("table", table);
 cmd.Parameters.AddWithValue("word", line);
 cmd.ExecuteNonQuery(); 

但是每次它尝试执行"执行非查询"行时,我都会收到以下错误:

An unhandled exception of type 'Npgsql.NpgsqlException' occurred in Npgsql.dll
Additional information: ERROR: 42601: syntax error at or near "("

我可以连接到我检查过的数据库。变量表和行在运行时也具有正确的值。我只是想不出问题是什么。.

有什么建议吗?

C# 中的 SQL 插入命令

据我所知,该表不能是参数。

但是,您可以做的是为此使用字符串连接/格式化:

string table = "table";
NpgsqlCommand cmd = new NpgsqlCommand(string.Format(@"INSERT INTO {0}(text) VALUES (:word);", table), con);

猜会起作用(没有测试它)。