我正在尝试使用简单的select语句和日期时间选择器从数据库中提取值。你能帮我解决一下这个问题吗?当我在查询中输入特定日期时,select语句在SQL中工作但我希望能够在datetimepicker上选择日期并能够检索该特定日期的数据。
这是到目前为止的代码:
Dim command As String = "select CUSORDER.ORDERID, CUSORDER.ORDERDATE,
CUSORDER.STAFFID, CUSTOMER.CUSTOMERID, CUSTOMER.CUSTOMERADD_1
FROM CUSORDER,CUSTOMER
WHERE CUSORDER.CUSTOMERID = CUSTOMER.CUSTOMERID AND
CUSORDER.ORDERDATE = '" & DateTimePicker1.Value.ToString & "'"
我是否使用正确的属性和格式才能执行此操作?
答案 0 :(得分:1)
您不应该连接字符串以获取您的sql查询。这可能会导致sql-injection漏洞,本地化问题或其他问题。您应该始终参数化您的查询:
Dim sql As String = "select CUSORDER.ORDERID, CUSORDER.ORDERDATE, CUSORDER.STAFFID, CUSTOMER.CUSTOMERID, CUSTOMER.CUSTOMERADD_1 FROM CUSORDER,CUSTOMER WHERE CUSORDER.CUSTOMERID = CUSTOMER.CUSTOMERID AND CUSORDER.ORDERDATE = @ORDERDATE"
Using con = New SqlConnection(YourConnectionString)
Using command = New SqlCommand(sql, con)
command.Parameters.AddWithValue("@ORDERDATE", DateTimePicker1.Value)
con.Open()
Using reader = command.ExecuteReader()
While reader.Read()
' ... '
End While
End Using
End Using
End Using
答案 1 :(得分:0)
如果有帮助,请执行以下操作:
Dim dteTemp As Date = DateTimePicker.value 'might help any injection code as the convert will fail.
Dim command As String = "select CUSORDER.ORDERID, CUSORDER.ORDERDATE, CUSORDER.STAFFID,
CUSTOMER.CUSTOMERID, CUSTOMER.CUSTOMERADD_1 FROM CUSORDER,CUSTOMER WHERE
(CUSORDER.CUSTOMERID = CUSTOMER.CUSTOMERID) AND
(CUSORDER.ORDERDATE = '" & dteTemp.ToString("yyyy/MM/dd HH:mm:ss") & "')"
日期的格式化避免了PC在SQL数据库本地的不同日期的问题。