使用ODBC / Net获取postgresql表中的存在和行数

时间:2012-06-07 15:11:01

标签: vb.net odbc postgresql-9.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...

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

1 个答案:

答案 0 :(得分: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

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