![](/img/trans.png)
[英]Insert data into table(from select) using 2 DataGridView c# windowsForm
[英]How to Select data from table 1 and insert into table 2 in PostgresQLusing C#
我正在尝试使用Visual Studio代码上的C#从一个表中获取数据并将其插入到Postgres的另一个表中。 我不断收到此错误:
An unhandled exception of type 'Npgsql.NpgsqlOperationInProgressException' occurred in System.Private.CoreLib.dll: 'A command is already in progress:
我猜想这是因为我的代码试图使用连接,因为它被第一个查询使用。 但是,我不知道如何解决它。
这是我的下面代码-原谅任何菜鸟错误,这是我第一次使用C#做到这一点。
using System;
using Npgsql;
class Sample
{
static void Main(string[] args)
{
// Specify connection options and open an connection
NpgsqlConnection conn = new NpgsqlConnection("Server=xxxxxxxx;User
Id=xxxxxxx;" +
"Password=xxxxxxx;Database=xxxxxxxx;");
conn.Open();
//Define select query
NpgsqlCommand cmd = new NpgsqlCommand("select * from table1", conn);
// Execute a query
NpgsqlDataReader dr = cmd.ExecuteReader();
//Define Insert query
NpgsqlCommand cmd1 = new NpgsqlCommand("insert into table2
values(dr[0],dr[1])", conn);
// Read all rows and output the first column in each row
while (dr.Read())
cmd1.ExecuteNonQuery();
// Close connection
conn.Close();
}
}
提前致谢!
您不必像这样执行操作,而只需一个命令(效率更高):
“从表1插入到表2(t21,t22)中选择t11m t12”
这样做还将解决错误“命令已在执行中”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.