I am trying to fetch data from one table and insert it into another table on Postgres using C# on Visual Studio code. 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.
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"
Doing this will also solve the error "A command is already in progress".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.