You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET加载Access数据库日期至ListView时遇数据类型不匹配错误求助

解决Access日期查询数据类型不匹配错误

错误原因

直接将日期转成字符串拼接进SQL语句,不同区域设置下的日期字符串格式无法被Access的Date/Time字段正确识别,导致数据类型不匹配,同时这种写法存在SQL注入风险。

修正方案:使用参数化查询

不管是插入还是查询操作,都通过参数传递日期值,让数据库自动处理类型转换。

1. 修正插入代码

strSQL = "INSERT INTO Table1 (DATEANDTIME) values (@DateTimeValue)"
accessCommand.CommandText = strSQL
accessCommand.Connection = accessConnection
' 添加日期参数,指定类型为Date
accessCommand.Parameters.Add("@DateTimeValue", DbType.Date).Value = DateTimePicker1.Value
accessCommand.ExecuteNonQuery()
accessCommand.Dispose()
accessDataReader.Close()
MsgBox("OK Done")

2. 修正查询代码

strSQL = "SELECT * from Table1 WHERE DATEANDTIME >= @StartDate AND DATEANDTIME <= @EndDate"
accessCommand.CommandText = strSQL
accessCommand.Connection = accessConnection
' 添加起始日期参数
accessCommand.Parameters.Add("@StartDate", DbType.Date).Value = DateTimePicker1.Value
' 添加结束日期参数
accessCommand.Parameters.Add("@EndDate", DbType.Date).Value = DateTimePicker2.Value
accessAdopter.SelectCommand = accessCommand
accessDataReader = accessCommand.ExecuteReader
ListViewLOCATION.Items.Clear()
While (accessDataReader.Read())
    ListViewLOCATION.Items.Add(accessDataReader("DATEANDTIME").ToString())
End While
accessCommand.Dispose()
accessDataReader.Close()

说明

参数化查询会自动处理日期类型与Access Date/Time字段的适配,无需手动转换字符串格式,彻底解决类型不匹配问题,同时避免SQL注入漏洞。

内容的提问来源于stack exchange,提问作者mr.neeo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:11:05