0

到目前为止,在 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 函数工作吗?

4

1 回答 1

2

我不知道您是否不想/不能更改您的查询,但我建议您使用该information_schema表而不是使用pg_tables. 我个人使用这种方法:

 public override bool TableExists(string tableName)
    {
        string sql = "SELECT * FROM information_schema.tables WHERE table_name = '" + tableName + "'";
        using (var con = new NpgsqlConnection(preparedConnectionString))
        {
            using (var cmd = new NpgsqlCommand(sql))
            {
                if (cmd.Connection == null)
                    cmd.Connection = con;
                if (cmd.Connection.State != ConnectionState.Open)
                    cmd.Connection.Open();

                lock (cmd)
                {
                    using (NpgsqlDataReader rdr = cmd.ExecuteReader())
                    {
                        try
                        {
                            if (rdr != null && rdr.HasRows)
                                return true;
                            return false;
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                }
            }
        }
    }

(不关心注射或类似的)

于 2013-07-15T09:32:20.090 回答