在VB.NET中检查SQL结果

时间:2009-12-02 10:10:04

标签: sql vb.net ms-access

我需要检查我的SQL语句是否从我用来存储数据的Access数据库返回任何结果。

我有这个代码atm:

        cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Computing Project\database.mdb;")
        cn.Open()
        cmd = New OleDbCommand("SELECT * FROM(" & roomvar.ToLower() & ") WHERE (((" & roomvar.ToLower() & ".date)=" & Chr(34) & dtpDate.Value.Date & Chr(34) & "))", cn)
        dr = cmd.ExecuteReader
            While dr.Read()

            End While
        End If
        dr.Close()

我希望能够检查(可能通过布尔值或其他东西)此结果返回查询。我正在使用VB.net。

由于

3 个答案:

答案 0 :(得分:4)

简单。在调用ExecuteReader后使用OleDbDataReader.HasRows属性。

    cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Computing Project\database.mdb;")
    cn.Open()
    cmd = New OleDbCommand("SELECT * FROM(" & roomvar.ToLower() & ") WHERE (((" & roomvar.ToLower() & ".date)=" & Chr(34) & dtpDate.Value.Date & Chr(34) & "))", cn)
    dr = cmd.ExecuteReader

    hasRows = dr.HasRows

    dr.Close()

答案 1 :(得分:1)

我想,简单的答案就是:

    Dim hasResults as Boolean = false
    cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Computing Project\database.mdb;")
    cn.Open()
    cmd = New OleDbCommand("SELECT * FROM(" & roomvar.ToLower() & ") WHERE (((" & roomvar.ToLower() & ".date)=" & Chr(34) & dtpDate.Value.Date & Chr(34) & "))", cn)
    dr = cmd.ExecuteReader
        While dr.Read()
             hasResults = true
        End While
    End If
    dr.Close()

我的vb语法有点生疏,但你明白了 但我不确定这是你真正想要的。

另一种变体可能是

Dim hasResults as Boolean = false
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Computing Project\database.mdb;")
cn.Open()
cmd = New OleDbCommand("SELECT 1 FROM(" & roomvar.ToLower() & ") WHERE (((" & roomvar.ToLower() & ".date)=" & Chr(34) & dtpDate.Value.Date & Chr(34) & "))", cn)
dr = cmd.ExecuteReader
    If dr.Read() Then
         hasResults = true
    End If
End If
dr.Close()

答案 2 :(得分:1)

Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Computing Project\database.mdb;")
    cn.Open()
    Using cmd As New OleDbCommand(String.Format("SELECT * FROM({0}) WHERE ((({0}.date)=""{1}""))", roomvar.ToLower(), dtpDate.Value.Date), cn)
        Using dr As OleDbDataReader = cmd.ExecuteReader()
            hasResults = dr.Read()
        End Using
    End Using
End Using

我强烈建议您查看将dtpDate值作为参数而不是命令文本中的文字值,例如:

Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Computing Project\database.mdb;")
    cn.Open()
    Using cmd As New OleDbCommand(String.Format("SELECT * FROM({0}) WHERE ((({0}.date)=?))", roomvar.ToLower()), cn)
        cmd.Parameters.Add("@dtpDate", OleDbType.Date).Value = dtpDate.Value.Date
        Using dr As OleDbDataReader = cmd.ExecuteReader()
            hasResults = dr.Read()
        End Using
    End Using
End Using