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

如何将DataGridView所有数据插入Access数据库?遇索引越界错误

问题分析与解决

首先,你遇到了两个核心问题:

  • 索引越界错误:代码里的Cells[1-5]是算术计算错误,1-5等于-4,这显然超出了单元格索引的有效范围(索引必须≥0且小于单元格集合的长度)。你需要分别获取每个字段对应的单元格值,而不是用这种错误的表达式。
  • SQL语句格式错误:你的INSERT语句要插入5个字段,但VALUES里只写了一个值,字段和值的数量不匹配,即使索引正确也会执行失败。

另外,直接用字符串拼接SQL语句存在SQL注入风险,而且如果单元格里包含单引号等特殊字符,会直接导致SQL语法错误,所以更推荐使用参数化查询来解决这些问题。

修正后的代码示例

方式1:参数化查询(推荐)

// 确保数据库连接已正确打开
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    // 跳过DataGridView的空白新行(如果启用了AllowUserToAddRows)
    if (dataGridView2.Rows[i].IsNewRow)
        continue;

    // 定义参数化的SQL语句,每个字段对应一个参数占位符
    string str1 = @"INSERT INTO tbl3(itemnamee, modelnumberr, pricese, countt, totalpricese) 
                    VALUES (@ItemName, @ModelNumber, @Price, @Count, @TotalPrice)";
    
    using (OleDbCommand cmd1 = new OleDbCommand(str1, con))
    {
        // 为每个参数赋值,处理单元格可能为空的情况
        cmd1.Parameters.AddWithValue("@ItemName", dataGridView2.Rows[i].Cells[0].Value ?? DBNull.Value);
        cmd1.Parameters.AddWithValue("@ModelNumber", dataGridView2.Rows[i].Cells[1].Value ?? DBNull.Value);
        cmd1.Parameters.AddWithValue("@Price", dataGridView2.Rows[i].Cells[2].Value ?? DBNull.Value);
        cmd1.Parameters.AddWithValue("@Count", dataGridView2.Rows[i].Cells[3].Value ?? DBNull.Value);
        cmd1.Parameters.AddWithValue("@TotalPrice", dataGridView2.Rows[i].Cells[4].Value ?? DBNull.Value);

        cmd1.ExecuteNonQuery();
    }
}

关键说明:

  1. 索引修正:这里假设你的DataGridView列顺序和数据库字段顺序一致,Cells[0]对应itemnamee,Cells[1]对应modelnumberr,以此类推。你需要根据自己实际的列索引调整这些数字(比如如果数据从第2列开始,就改成Cells[1]、Cells[2]等)。
  2. 跳过新行:如果DataGridView启用了AllowUserToAddRows,最后一行是空白的待编辑行,需要跳过它,避免插入空数据。
  3. 参数化查询:用@参数名代替直接拼接字符串,既避免了SQL注入,也解决了特殊字符导致的语法错误,同时处理了单元格为空的情况(用?? DBNull.Value把null转换为数据库能识别的空值)。

方式2:字符串拼接(不推荐)

如果你暂时不想用参数化,至少要修正索引和SQL格式,但请注意这种方式的风险:

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    if (dataGridView2.Rows[i].IsNewRow)
        continue;

    // 分别获取每个单元格的值,手动转义单引号避免SQL语法错误
    string itemName = dataGridView2.Rows[i].Cells[0].Value?.ToString().Replace("'", "''") ?? "";
    string modelNumber = dataGridView2.Rows[i].Cells[1].Value?.ToString().Replace("'", "''") ?? "";
    string price = dataGridView2.Rows[i].Cells[2].Value?.ToString().Replace("'", "''") ?? "";
    string count = dataGridView2.Rows[i].Cells[3].Value?.ToString().Replace("'", "''") ?? "";
    string totalPrice = dataGridView2.Rows[i].Cells[4].Value?.ToString().Replace("'", "''") ?? "";

    string str1 = $"INSERT INTO tbl3(itemnamee, modelnumberr, pricese, countt, totalpricese) VALUES('{itemName}', '{modelNumber}', '{price}', '{count}', '{totalPrice}');";
    
    OleDbCommand cmd1 = new OleDbCommand(str1, con);
    cmd1.ExecuteNonQuery();
}

这种方式需要手动转义单引号(把'换成''),否则如果单元格内容包含单引号,SQL语句会直接报错,而且存在注入风险,所以强烈推荐使用参数化查询。

额外检查点

  • 确认你的DataGridView列数量足够,比如如果用Cells[4],那DataGridView至少要有5列(索引从0到4)。
  • 确认数据库连接con已经正确打开,并且没有提前关闭。
  • 确认数据库表tbl3的字段类型和DataGridView中的数据类型匹配,比如pricese如果是数值类型,不要插入字符串格式的数据。

内容的提问来源于stack exchange,提问作者Best Movies

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:52:45