【问题标题】:How Can I add more then one query in one connection (Visual Studio C# to PostgreSQL)如何在一个连接中添加多个查询(Visual Studio C# 到 PostgreSQL)
【发布时间】:2021-02-25 06:47:03
【问题描述】:

我将数据添加到数据库

NpgsqlConnection conn1 = new NpgsqlConnection("Server=localhost;Port=5432;Database=test;User Id=postgres;Password=postgres;");
conn.Open();

NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "SELECT * FROM test";
NpgsqlDataReader dr = comm.ExecuteReader();

if (dr.HasRows)
{
    dt.Load(dr);
    dataGridView1.DataSource = dt;
}

comm.Dispose();
conn.Close();

到目前为止一切都很好 但我想在一个连接中添加多个查询 例如

comm.CommandText = "SELECT * FROM test";
NpgsqlDataReader dr = comm.ExecuteReader();

// some code for view data in dataGridView1

comm.CommandText = "SELECT * FROM test1";
NpgsqlDataReader dr = comm.ExecuteReader();

// and some code for view data in dataGridView2

但我做不到

或者可能使用事务,但我不知道如何使用它。

【问题讨论】:

  • 你得到了什么......像“已经有一个与此连接相关联的开放阅读器”之类的东西?关闭一个连接实际上并没有关闭一个连接,它只是将它返回到一个被 Open 借用的连接池中;随时打开和关闭它们,每次查询一次(除非您需要一个似乎没有出现的事务),它会没事的。顺便说一句,与您在这里所做的相比,处理数据的方法更简单

标签: c# postgresql connection


【解决方案1】:

使用数据适配器让生活更轻松:

var conn = "Server=localhost;Port=5432;Database=test;User Id=postgres;Password=postgres;"

var da = new NpgsqlDataAdapter("SELECT * FROM one", conn);
var dt = new DataTable();
da.Fill(dt);
grid1.DataSource = dt;

da = new NpgsqlDataAdapter("SELECT * FROM two", conn);
dt = new DataTable();
da.Fill(dt);
grid2.DataSource = dt;

【讨论】:

  • 当我使用此代码时,我的 dataGridView 为空。我的“程序”应该像这样工作。有 3 个 textBox-es、1 个按钮和 1 个 dataGridView 我填充 textBox-es 并单击按钮。然后我将此数据添加到测试表并使用测试表中的数据刷新 dataGridView
  • 当我使用此代码时,我的 dataGridView 为空 - 您希望我如何根据您提供的信息进行调试?可以肯定的是,您必须将我在此处编写的代码转换为您放入程序中的代码,因此您需要提供更多信息。使用调试器对其进行单步调试,看看是什么指出事情出错了:您是否在数据表中获取数据?您是否将其链接到正确的网格?你有没有发现任何异常并把它们扔掉?
猜你喜欢
  • 2018-04-21
  • 2016-03-05
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多