VB.NET读取M3U查询SQL绑定DataGridView报索引越界错误
与DataTable相关的错误原因及修复
核心原因(直接触发错误)
- 未检查DataTable是否有数据就强行访问行:当M3U文件里的某条路径在
dbo.MP3Tracks表中不存在时,Adapter.Fill(Table)执行后Table.Rows.Count为0。此时代码直接调用Table.Rows(0),必然抛出IndexOutOfRangeException(即你看到的“there is no line at position 0”错误)。当前代码默认所有路径都能匹配到数据库记录,完全没处理查询无结果的场景。
间接引发DataTable错误的循环逻辑问题
- 循环内两次调用
sr.ReadLine():第一次在循环体开头读取行,第二次在循环末尾又读取,导致跳过了一半的行。当读到文件末尾时,sString变为Nothing,但循环仍会执行查询逻辑,此时用空字符串作为查询条件,必然查不到数据,Table为空,再次触发上述的行访问错误。
修复后的代码示例
Dim sString As String = "" Dim i As Integer = 0 Dim sr As New StreamReader(sPath) DataGridView.Rows.Clear() ConDBMusic.Open() ' 修正循环逻辑,统一在合适位置读取行 sString = sr.ReadLine() Do While sString IsNot Nothing If Not String.IsNullOrEmpty(sString) Then ' 用参数化查询替代字符串拼接,避免注入和特殊字符问题 sSqlSelect = "Select * From dbo.MP3Tracks Where MP3_FileName = @FilePath" Dim Adapter As New SqlDataAdapter(sSqlSelect, ConDBMusic) Adapter.SelectCommand.Parameters.AddWithValue("@FilePath", sString) Dim Table As New DataTable() Adapter.Fill(Table) ' 先检查DataTable是否有数据,再访问行 If Table.Rows.Count > 0 Then DataGridView.Rows.Add() DataGridView.Rows(i).Cells(0).Value = Table.Rows(0)("MP3_Artist") DataGridView.Rows(i).Cells(1).Value = Table.Rows(0)("Mp3_Album") DataGridView.Rows(i).Cells(2).Value = Table.Rows(0)("MP3_Year") i += 1 End If End If sString = sr.ReadLine() Loop sr.Close() ConDBMusic.Close()
额外优化说明
- 参数化查询不仅能避免SQL注入风险,还能解决路径中含单引号、特殊字符导致的查询失败问题。
- 增加空字符串检查,可跳过M3U文件中的注释行或空行,避免无效查询。
内容的提问来源于stack exchange,提问作者Paul1957
相关产品推荐
相关产品推荐

