1

我通过 ODBC 将 PostgreSQL 数据库与 VB.net 一起使用,一切正常。
示例代码:

    Dim reader As OdbcDataReader
    Dim btCommand As OdbcCommand
    Dim mCmd As OdbcCommand
    Dim mCon as OdbcConnection

    mCon.ConnectionString = "Dsn=PostgreSQL30;database=mydb;server=127.0.0.1;port=myport;uid=myuid;pwd=mypass"
    mCon.Open()
    btCommand = New OdbcCommand("BEGIN TRANSACTION", mCon)
    mCmd = New OdbcCommand("SELECT dtbl_id, name, meas, price, qty, flag, kind FROM mytable WHERE dtbl_id >=" & brr.ToString & " ORDER BY dtbl_id LIMIT " & page.ToString, mCon)
    reader = mCmd.ExecuteReader()
    While (reader.Read())
        Dim n As Integer = DataGridView1.Rows.Add()
        With DataGridView1.Rows.Item(n)
            .Cells(0).Value = reader.GetValue(0).ToString()
            .Cells(1).Value = reader.GetValue(1).ToString()
            .Cells(2).Value = reader.GetValue(2).ToString()

    ... etc...

但我不知道如何使用该系统(odbc)检查表是否存在以及有多少行包含到 VB 变量中,因此任何建议都将受到高度赞赏。

4

1 回答 1

2

自己解决了问题。

如果表不存在,texists 将以 -1 结束,如果表存在并且没有插入任何行,则以 0 结束,或者以表示表中存在的行数的任何整数结束。

代码:

    Dim texists As Integer = -1        
    btCommand = New OdbcCommand("SELECT 1 FROM pg_tables WHERE tablename='mytable'", mCon)
    reader = btCommand.ExecuteReader()
    While (reader.Read())
        If reader.GetValue(0) = 1 Then texists = 0
    End While

    If texists >= 0 Then
        btCommand = New OdbcCommand("SELECT COUNT(*) from mytable", mCon)
        Try
            reader = btCommand.ExecuteReader()
            While (reader.Read())
                texists = Val(reader.GetValue(0).ToString())
            End While
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly)
        End Try
    End If

在此之后,根据 texists 的值,我们可以创建一个表,终止程序或继续工作。

于 2012-06-09T09:02:27.053 回答