[英]PostgreSQL, Get database exists with Npgsql
I cant get reliable checking for database existence in NET/Npgsql at my program startup. 在程序启动时,我无法在.NET / Npgsql中检查数据库是否存在。
Here is code: 这是代码:
Public Function dbExists(ByVal _dbName As String) As Boolean
Dim retval As Boolean = False
Using mCon As New NpgsqlConnection(String.Format( _
"Server={0};Port={1};User Id={2};Password={3};", _
dbserver, dbport, "postgres", dbpass))
Try
mCon.Open()
Using nCom = New NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname='" + _dbName + "'", mCon)
retval = CBool(nCom.ExecuteScalar())
End Using
Catch ex As Exception
retval = False
End Try
End Using
Return retval
End Function
This function return True no matter database exists or not. 无论数据库是否存在,此函数都返回True。 I also try with null checking on ExecuteScalar, getting Count(*) and all what I can without better result.
我也尝试对ExecuteScalar进行空检查,得到Count(*)以及我所能得到的所有结果。
What to do to get it working? 如何让它运作?
Null checking on 'ExecuteScalar()' works for me (PostgreSQL 9.3 and Npgsql 2.0.12). Null检查'ExecuteScalar()'对我有用(PostgreSQL 9.3和Npgsql 2.0.12)。 Are you checking 'ExecuteScalar() == null'?
你在检查'ExecuteScalar()== null'吗?
ExecuteScalar will return a .NET null
not DBNull.Value
(since it is not a record with a null value, it signifies no matching result). ExecuteScalar将返回.NET
null
而不是 DBNull.Value
(因为它不是具有空值的记录,它表示没有匹配的结果)。
I'm not a VB person but here's how I achieved it in C#: 我不是VB的人,但这是我在C#中实现的方式:
bool dbExists;
using (NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=postgres;User Id=postgres;Password=testpass"))
{
conn.Open();
string cmdText = "SELECT 1 FROM pg_database WHERE datname='temp'";
using (NpgsqlCommand cmd = new NpgsqlCommand(cmdText, conn))
{
dbExists = cmd.ExecuteScalar() != null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.