如何在 C# 中从 PostgreSQL 中获取所选行的值? [英] How to get the value of selected row from PostgreSQL in C#?
本文介绍了如何在 C# 中从 PostgreSQL 中获取所选行的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用带有 C# 和 Npgsql 库的 PostgreSQL 数据库.
I am using PostgreSQL database with C# and the Npgsql library.
现在我可以选择表中的最后一行,但我不知道如何为其分配 C# 变量.我知道我的选择有效,因为我之前已经成功编辑了我的最后一个条目.
Right now I can select the last row in my table, but I can not figure out how to assign a C# variable to it. I know that my selection works, because I have successfully edited my last entry before.
您可以在下面找到我的代码.请注意,我没有粘贴其余的方法,因为我认为它们无关紧要.
You can find my code below. Note that I have not pasted the rest of the methods as I think they are irrelevant.
public void myMethod()
{
this.OpenConn(); //opens the connection
string sql = "SELECT id FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'customers' ORDER BY id DESC, LIMIT 1";
using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
{
int id = 0; //instead of '0' I want it to be equal to the ID value from the row
//something like "int id = sqlSelection.id;" -- this obviously doesn't work
this.CloseConn(); //close the current connection
}
}
推荐答案
您可以通过使用特定的 DataReader 来实现此目标:
You could achieve this goal by using the specific DataReader:
public void myMethod()
{
this.OpenConn(); //opens the connection
string sql = "SELECT id FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'customers' ORDER BY id DESC, LIMIT 1";
using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
{
int val;
NpgsqlDataReader reader = command.ExecuteReader();
while(reader.Read()){
val = Int32.Parse(reader[0].ToString());
//do whatever you like
}
this.CloseConn(); //close the current connection
}
}
有用的笔记
- 在某些情况下,ExecuteScalar 是一个不错的选择
- Npgsql 文档
- In some contexts ExecuteScalar is a good alternative
- Npgsql documentation
这篇关于如何在 C# 中从 PostgreSQL 中获取所选行的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文