如何使用C#中的Npgsql获取用户计算机上所有可用PostgreSQL数据库的列表?
答案 0 :(得分:3)
在postgreSQL中有两种方法可以做到:
\l
SELECT datname FROM pg_database;
答案 1 :(得分:0)
使用Npgsql
可以使用以下代码段:
IEnumerable<string> GetDatabaseNames()
{
var connStrBuilder = new NpgsqlConnectionStringBuilder();
connStrBuilder.Host = "localhost";
connStrBuilder.Username = "theduck";
connStrBuilder.Password = "password123";
connStrBuilder.Database = "postgres"; // this database is always present
using (var conn = new NpgsqlConnection(connStrBuilder.ConnectionString))
{
conn.Open();
using (var command = new NpgsqlCommand("SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname;", conn))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return reader.GetString(0);
}
}
}
}