0
直到現在我沒有看到在Windows上使用PostgreSQL數據庫時使用Npgsql驅動程序而不是ODBC的任何區別。但現在我找到了一個。檢查PostgreSQL表是否存在與Npgsql
我有這樣的代碼檢查表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
有了這個代碼,我得到真,如果特定的表中確定的數據庫或存在虛假,否則。
當我嘗試使用,而不是ODBC Npgsql的功能非常相似:
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函數工作?
爲什麼你使用'的ExecuteNonQuery()'?你**正在運行一個查詢,所以你不應該使用'executeQuery()'(或類似的東西 - 我不知道.Net) –
你好「名字」。通常你的邏輯非常好。出於某種原因,MS ODBC返回的查詢值爲executeNonQuery,但Npgsql意外地沒有。直到現在我還不知道那個區別。但是這裏是ExecuteScalar,它返回一個(這樣的)查詢的第一行或值。這樣,用ExecuteScalar我得到了預期的顯示查詢結果並讓我的Npgsql函數正常工作。謝謝你指點我正確的方向。 –
你能舉一個例子嗎?我會很高興upvote。 –