简体   繁体   中英

Get database list in Npgsql

如何在C#使用Npgsql用户计算机上所有可用PostgreSQL数据库的列表?

在 postgreSQL 中有两种方法可以做到:

  • \\l
  • SELECT datname FROM pg_database;

Using Npgsql You can use such code snippet:

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);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM