如何在 C# 中从 PostgreSQL 中获取所选行的值?

编程入门 行业动态 更新时间:2024-10-25 02:22:18
本文介绍了如何在 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 中获取所选行的值?

本文发布于:2023-11-16 16:20:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605887.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所选   如何在   PostgreSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!