到目前为止,在 Windows 上使用 PostgreSQL 数据库时,使用 Npgsql 驱动程序而不是 ODBC 没有任何区别。但现在我找到了一个。
我有这样的代码来检查表是否存在 ODBC:
Public Function dbTableExists(ByVal dbTable As String, ByVal dbName As String) As Boolean
Dim retval As Boolean = False
Dim nCon As New OdbcConnection
Dim btCommand As OdbcCommand = Nothing
nCon.ConnectionString = "Dsn=" + dbDsn + _
";database=" + dbName & _
";server=" + dbServer + _
";port=" + dbPort + _
";uid=" + dbUser + _
";pwd=" + dbPass
Try
nCon.Open()
btCommand = New OdbcCommand("SELECT 1 FROM pg_tables WHERE tablename='" & dbTable + "'", nCon)
retval = CBool(btCommand.ExecuteNonQuery())
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
retval = False
End Try
Return retval
End Function
使用此代码,如果确定的数据库中存在特定表,则我得到 True,否则得到 False。
当我尝试使用 Npgsql 而不是 ODBC 函数时非常相似:
Public Function tExists(ByVal dbTable As String, ByVal dbName As String) As Boolean
Dim retval As Boolean = False
Dim btCommand As NpgsqlCommand = Nothing
Dim nCon As New NpgsqlConnection(String.Format( _
"Server={0};Port={1};User Id={2};Password={3};Database={4};", _
dbServer, dbPort, dbUser, dbPass, dbName))
Try
nCon.Open()
btCommand = New NpgsqlCommand("SELECT 1 FROM pg_tables WHERE tablename='" & dbTable + "'", nCon)
retval = CBool(btCommand.ExecuteNonQuery())
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
retval = False
End Try
Return retval
End Function
但这不会按预期工作。
无论是否存在特定表,我总是得到 True 作为结果。
知道如何让 Npgsql 函数工作吗?