简体   繁体   English

如何从表1中选择数据并将其插入PostgresQLusing C#中的表2中

[英]How to Select data from table 1 and insert into table 2 in PostgresQLusing C#

I am trying to fetch data from one table and insert it into another table on Postgres using C# on Visual Studio code. 我正在尝试使用Visual Studio代码上的C#从一个表中获取数据并将其插入到Postgres的另一个表中。 I keep getting this error: 我不断收到此错误:

An unhandled exception of type 'Npgsql.NpgsqlOperationInProgressException' occurred in System.Private.CoreLib.dll: 'A command is already in progress:

I am guessing this is happening because my code tries to use the connection as it is being used by the first query. 我猜想这是因为我的代码试图使用连接,因为它被第一个查询使用。 I, however, do not know how to fix it. 但是,我不知道如何解决它。

Here is my code below - Forgive any rookie mistakes, this is my first time ever using C# to do this. 这是我的下面代码-原谅任何菜鸟错误,这是我第一次使用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();
 }
}

Thanks in Advance! 提前致谢!

You don't do it like this, but in a single command(is much more efficient): 您不必像这样执行操作,而只需一个命令(效率更高):

"INSERT INTO table2(t21, t22) SELECT t11m t12 FROM table1" “从表1插入到表2(t21,t22)中选择t11m t12”

Doing this will also solve the error "A command is already in progress". 这样做还将解决错误“命令已在执行中”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM