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

SQL插入患者数据时触发索引越界错误求助

问题排查与修复方案

1. 触发错误的核心原因

你的SQL插入语句定义了8个占位符({0}到{7}),但调用string.Format时仅传入了7个参数(Name、Phone、Address、Dateofbirth、Gender、Allergies、Patmedhistory),参数数量与占位符数量不匹配,这就是抛出Index (zero based) must be greater than or equal to zero and less than the size of the argument list.错误的直接原因。

修复方式:

  • 先确认Paitent.Tbl表的实际字段数量:
    • 如果表确实有8个字段,补充缺失的对应参数(比如自增ID无需手动传入,则删除SQL中对应的占位符);
    • 如果表只有7个字段,修改SQL语句的占位符数量为7个,示例:
      string Query = @"insert into Paitent.Tbl 
      Values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
      

2. 其他潜在问题修复

(1) 输入验证逻辑漏洞

PatphoneTB.Text == " "仅检查单个空格,用户输入多空格或空字符串会绕过验证,统一改为Trim后判断空值:

if (string.IsNullOrWhiteSpace(PatnameTB.Text) || 
    string.IsNullOrWhiteSpace(PatphoneTB.Text) || 
    string.IsNullOrWhiteSpace(PatadressTB.Text) || 
    string.IsNullOrWhiteSpace(PatdobTB.Text) || 
    PatgenderCB.SelectedIndex == -1 || 
    string.IsNullOrWhiteSpace(PatallergiesTB.Text) || 
    string.IsNullOrWhiteSpace(PatmedhistoryTB.Text)) 
{
    MessageBox.Show("Missing Data!!!");
}

(2) 高危SQL注入风险

当前用string.Format拼接SQL语句存在严重注入风险,必须改用参数化查询,示例(适配SQL Server):

// 显式指定字段名,避免字段顺序变动引发问题
string Query = @"insert into Paitent.Tbl 
(Name, Phone, Address, DateOfBirth, Gender, Allergies, MedHistory)
Values(@Name, @Phone, @Address, @DateOfBirth, @Gender, @Allergies, @MedHistory)";

using (SqlCommand cmd = new SqlCommand(Query, Con))
{
    cmd.Parameters.AddWithValue("@Name", Name);
    cmd.Parameters.AddWithValue("@Phone", Phone);
    cmd.Parameters.AddWithValue("@Address", Address);
    cmd.Parameters.AddWithValue("@DateOfBirth", Dateofbirth);
    cmd.Parameters.AddWithValue("@Gender", Gender);
    cmd.Parameters.AddWithValue("@Allergies", Allergies);
    cmd.Parameters.AddWithValue("@MedHistory", Patmedhistory);
    
    Con.Open();
    cmd.ExecuteNonQuery();
    Con.Close();
}

(3) 患者列表未更新的原因

由于参数不匹配抛出异常,代码执行会中断,ShowPatients()和后续提示框都不会运行。修复参数问题后,异常消失,代码会正常执行ShowPatients(),列表即可正常更新。

内容的提问来源于stack exchange,提问作者ugur ozkan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:15:30