VB.NET中SQLite日期区间查询问题:DataGridView无结果
问题分析与解决方案
你的核心问题在于SQL查询语句里直接写了字符串字面量'TextBox4.text'和'TextBox5.text',而不是把这两个文本框的实际值代入查询。SQL引擎会把这两个当作固定的日期字符串去匹配,自然找不到任何数据。
另外你的日期格式化代码用Substring容易出错(比如不同系统的日期格式可能存在差异),同时建议使用参数化查询,既安全又能避免字符串拼接的格式问题。
修复步骤
1. 优化日期格式化代码
不要用Substring拆分日期,直接用DateTime.ToString("yyyy-MM-dd")就能得到你需要的格式,更简洁可靠:
' 格式化开始日期 TextBox4.Text = DateTimePicker2.Value.ToString("yyyy-MM-dd") ' 格式化结束日期 TextBox5.Text = DateTimePicker3.Value.ToString("yyyy-MM-dd")
2. 使用参数化查询重构SQL语句
参数化查询是处理动态值的最佳实践,能避免SQL注入,同时不用手动处理字符串引号的问题:
Dim Sorgu As String = "select * from mytable where strftime('%Y-%m-%d', tarih) between @StartDate and @EndDate"
然后给SQLCommand添加对应参数:
MyCmd.Parameters.AddWithValue("@StartDate", TextBox4.Text) MyCmd.Parameters.AddWithValue("@EndDate", TextBox5.Text)
3. 完整修正后的代码
Private Sub YourTargetSub() ' 替换成你实际的子过程名称 ' 优化日期格式化逻辑 TextBox4.Text = DateTimePicker2.Value.ToString("yyyy-MM-dd") TextBox5.Text = DateTimePicker3.Value.ToString("yyyy-MM-dd") Dim Yol As String = "Data Source=database1.s3db;version=3;new=False" Using MyConn As New SQLiteConnection(Yol) If MyConn.State = ConnectionState.Closed Then MyConn.Open() End If ' 采用参数化查询避免硬编码与注入风险 Dim Sorgu As String = "select * from mytable where strftime('%Y-%m-%d', tarih) between @StartDate and @EndDate" Using MyCmd As New SQLiteCommand(Sorgu, MyConn) ' 绑定查询参数 MyCmd.Parameters.AddWithValue("@StartDate", TextBox4.Text) MyCmd.Parameters.AddWithValue("@EndDate", TextBox5.Text) Dim Da As New SQLiteDataAdapter(MyCmd) Dim Dt As New DataTable Da.Fill(Dt) Dim Bs As New BindingSource With {.DataSource = Dt} DataGridView1.DataSource = Bs Bs.MoveLast() End Using End Using End Sub
额外说明
- 为什么不推荐字符串拼接?比如
"between '" & TextBox4.Text & "' and '" & TextBox5.Text & "'":这种写法存在SQL注入漏洞,而且如果日期格式异常(比如包含单引号)会直接导致SQL语法错误。 - 你的
DataGridView显示带时间的日期,但strftime('%Y-%m-%d', tarih)已经把数据库中的日期转换为纯日期格式,和文本框的格式完全匹配,所以查询逻辑本身是合理的。
内容的提问来源于stack exchange,提问作者Tanya
相关产品推荐
相关产品推荐

