Imports System.Data
Imports System.Data.SqlClient
Public Class Form2
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As SqlCommand
Dim conn As SqlConnection
Dim dr2 As SqlDataReader
Dim sql = "SELECT room number,date,ddate FROM date WHERE room number = '" & nametxt.Text & "' AND date >= '" & DateTimePicker1.Text & "'AND ddate <= '" & DateTimePicker1.Text & "'OR Room number = '" & nametxt.Text & "'AND date = '" & DateTi mePicker1.Text & "' "
conn = New SqlConnection("Data Source=zahid\sqlexpress;Initial Catalog=test;Integrated Security=True")
conn.Open()
cmd = New SqlCommand(sql, conn)
Try
dr2 = cmd.ExecuteReader
If dr2.Read = True Then
MessageBox.Show("room not available...")
Else
MessageBox.Show("Login Successful...")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
If conn.State <> ConnectionState.Closed Then
conn.Close()
End If
End Sub
End Class
问问题
317 次
1 回答
1
当您有一个名称中包含空格的字段时,您应该将其括在方括号中
Dim sql = "SELECT [room number,date,ddate FROM date WHERE [room number] = " & _
"'" & nametxt.Text & "' AND date >= '" & DateTimePicker1.Text & _
"'AND ddate <= '" & DateTimePicker1.Text & "'OR [Room number] = '" & _
"nametxt.Text & "'AND date = '" & DateTimePicker1.Text & "' "
说您应该绝对删除字符串连接并使用参数化查询。我还放了一个括号来更好地对逻辑条件进行分组
Dim sql = "SELECT [room number],date,ddate FROM date WHERE " & _
"([room number] = @rnum AND date >= @dt AND ddate <= @dt) " & _
" OR ([Room number] = @rnum AND date = @dt)"
现在查询文本已使用参数进行了简化,您可以轻松地看到不需要条件 OR,因为它已经包含在第一个块中。
所以你的代码可以写成
Dim sql = "SELECT [room number],date,ddate FROM date WHERE " & _
"[room number] = @rnum AND date >= @dt AND ddate <= @dt "
Using conn = New SqlConnection("Data Source=zahid\sqlexpress;Initial Catalog=test;Integrated Security=True")
Using cmd = New SqlCommand(sql, conn)
conn.Open()
cmd.Parameters.AddWithValue("@rnum", nametxt.Text)
cmd.Parameters.AddWithValue("@dt", DateTimePicker1.Value)
Try
Using dr2 = cmd.ExecuteReader
' Probably this test is wrong....
If dr2.Read = True Then
MessageBox.Show("room not available...")
Else
MessageBox.Show("Login Successful...")
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
If conn.State <> ConnectionState.Closed Then
conn.Close()
End If
于 2013-07-22T07:34:58.657 回答