![](/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.