此代码返回零行数,但appointment
表中有2行。
我评论过的msgbox是检查日期是否正确,格式是否正确,并将日期显示为2014/08/09。数据库中的预约日期为2014/08/09,共有2条记录(仅有2条记录)。记录计数变量显示为0。
表名(直接复制并粘贴)为Appointments
,列为AppointmentDate
。
connectDatabase
子例程连接到数据库成功,因为每当我连接到数据库时它都会使用它,所以它正确,因为我在使用相同的子例程运行此代码之前正确连接到其他表。
Command.text
包含
SELECT * FROM Appointments WHERE AppointmentDate = 2014/08/09
不知道要指定的其他细节。
Private Sub frmAppointments_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'load appointments
LoadAppointments(dtpAppointmentDate.Value.Date)
End Sub
Public Sub LoadAppointments(whichdate As Date)
Dim sqlcmd As New OleDb.OleDbCommand
'set connection
ConnectDatabase()
With frmAppointments
'MsgBox(whichdate)
M_connDB.Open()
'fetch records from database
sqlcmd.Connection = M_connDB
sqlcmd.CommandText = "SELECT * FROM Appointments WHERE AppointmentDate = " & whichdate
.dataAdapterAppointments = New OleDb.OleDbDataAdapter(sqlcmd.CommandText, M_connDB)
'first clear data table to prevent duplicates
.dataTableAppointments.Rows.Clear()
.dataAdapterAppointments.Fill(.dataTableAppointments)
M_connDB.Close()
Dim rowindex As String
Dim iy As Long
Dim recordcount As Long
'check if any records exist
recordcount = .dataTableAppointments.Rows.Count
If Not recordcount = 0 Then
For iy = 0 To .dataTableAppointments.Rows.Count
For Each row As DataGridViewRow In .dtgrdAppointments.Rows
If row.Cells(0).Value = .dataTableAppointments.Rows(iy).Item(6) Then
rowindex = row.Index.ToString()
MsgBox(.dtgrdAppointments.Rows(rowindex).Cells(0).Value, vbInformation + vbOKOnly, "MSG")
Exit For
End If
Next
Next iy
Else
MsgBox("No Appointments for selected date.", vbInformation + vbOKOnly, "No Appoinments")
End If
End With
答案 0 :(得分:1)
使用sql-parameters而不是string-concatenation。这应该在MS Access中起作用:
sqlcmd.CommandText = "SELECT * FROM Appointments WHERE AppointmentDate = ?"
sqlcmd.Parameters.AddWithValue("AppointmentDate", whichdate)
这可以防止转换或本地化问题,甚至更重要的是-sql-injection。
答案 1 :(得分:0)
2014/08/09
没有引号,使其成为数学表达式(2014除以8除以9)。当然,您的表没有行,其日期与该表达式的结果相匹配。但是不要加上引号。而是添加一个参数。
答案 2 :(得分:0)
我不是VB,所以我用C#编写。我的观点是,指定数据类型也是更好的选择:
sqlcmd.CommandText = "SELECT * FROM Appointments WHERE AppointmentDate=@whichdate";
sqlcmd.Parameters.Add("@whichdate", SqlDbType.Date).Value = whichdate;