VB.NET操作SQLite搜索时出现LIKE语法错误的技术问询
解决VB.NET操作SQLite搜索时的SQL语法错误
问题根源
- SQL语句拼接缺失空格:拼接
WHERE子句时,FROM DICOMStudies与WHERE之间没有空格,导致生成的SQL出现DICOMStudiesWHERE这种无效语法片段,触发near 'like' syntax error错误。 - 冗余参数定义:代码中添加了
@keyword1参数,但SQL语句并未使用该参数,属于无效冗余代码。
修复后的代码修改
调整SearchButton_Click方法中的SQL拼接和参数部分:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click If connection.State = ConnectionState.Closed Then connection.Open() End If Try If String.IsNullOrEmpty(KeywordTextBox.Text.Trim()) Then UpdateDatabiding() Exit Sub End If ' 修复:在WHERE前添加空格 sql = "SELECT StudyDate,PatientNam,StudyModal,StudyDescr,PatientsAg,PatientID FROM DICOMStudies " sql &= "WHERE PatientNam LIKE @keyword2" command.CommandType = CommandType.Text command.CommandText = sql command.Parameters.Clear() Dim KeywordString As String = String.Format("%{0}%", KeywordTextBox.Text) ' 移除未使用的@keyword1参数 command.Parameters.AddWithValue("@keyword2", KeywordString) UpdateDatabiding(command) Catch ex As Exception MessageBox.Show("Search Error: " & ex.Message.ToString(), "Error Message : iBasskung Tutorial.", MessageBoxButtons.OK, MessageBoxIcon.Error) Finally connection.Close() KeywordTextBox.Focus() End Try End Sub
额外优化建议
- 避免字符串拼接导致的语法问题,可使用VB.NET字符串插值(需VB.NET 14及以上版本)简化SQL语句:
sql = $"SELECT StudyDate,PatientNam,StudyModal,StudyDescr,PatientsAg,PatientID FROM DICOMStudies WHERE PatientNam LIKE @keyword2" - 用
Using语句管理数据库连接,自动释放资源防止连接泄漏,例如在数据绑定方法中:Using tempConn As New SQLiteConnection(conString) tempConn.Open() ' 执行查询、填充数据集等操作 End Using
内容的提问来源于stack exchange,提问作者Mohamed Magdy
相关产品推荐
相关产品推荐

