System.FormatException异常修复:C#数据库更新报错及字段异常排查
解决C#数据更新时的System.FormatException异常问题
问题排查与修复步骤:
- 移除无效参数:代码里添加了
@ad2参数,但SQL更新语句中并未用到该参数,直接删除komut.Parameters.AddWithValue("@ad2", textBox6.Text);这一行。 - 修正类型转换逻辑:
Convert.ToInt16(textBox6.Text)会在输入内容不是有效短整型时抛出FormatException,建议用安全转换方法做输入验证:if (!Int16.TryParse(textBox6.Text, out short no)) { MessageBox.Show("请输入有效的编号!"); return; } komut.Parameters.AddWithValue("@no", no); - 核对数据库字段名:你提到字段名变为
hasta_id,但当前SQL语句用mno=@no作为WHERE条件,大概率是主键字段名匹配错误。如果表的主键是hasta_id,需同步修改SQL语句和参数对应关系:
修正后的SQL语句:
同时要确保UPDATE tablo_1 SET ad=@ad,soyad=@soyad,tc_kimlik=@tc_kimlik,dttarih=@dttarih,rahatsizlik=@rahatsizlik,mno=@mno WHERE hasta_id=@no@no的类型和hasta_id字段类型一致(如果是int类型,需改用Int32.TryParse)。
修正后的完整代码示例:
private void btnGuncelle_Click(object sender, EventArgs e) { // 验证输入编号的有效性 if (!Int16.TryParse(textBox6.Text, out short hastaId)) { MessageBox.Show("请输入有效的患者编号!"); return; } string sorgu = "UPDATE tablo_1 SET ad=@ad,soyad=@soyad,tc_kimlik=@tc_kimlik,dttarih=@dttarih,rahatsizlik=@rahatsizlik,mno=@mno WHERE hasta_id=@no"; komut = new SqlCommand(sorgu, baglanti); komut.Parameters.AddWithValue("@no", hastaId); komut.Parameters.AddWithValue("@ad", txtAdi.Text); komut.Parameters.AddWithValue("@soyad", txtSoyadi.Text); komut.Parameters.AddWithValue("@tc_kimlik", txtKimlik.Text); komut.Parameters.AddWithValue("@rahatsizlik", txtRahatsizlik.Text); komut.Parameters.AddWithValue("@dttarih", dateTimePicker1.Value); // 若mno为数字类型,同样需要做类型验证转换 komut.Parameters.AddWithValue("@mno", textBox6.Text); try { baglanti.Open(); komut.ExecuteNonQuery(); MessageBox.Show("数据更新成功!"); } catch (Exception ex) { MessageBox.Show("更新失败:" + ex.Message); } finally { baglanti.Close(); } HastaGetir(); }
额外注意事项:
- 数据库连接建议用
using语句自动释放资源,避免连接泄漏:using (SqlConnection conn = new SqlConnection(你的连接字符串)) { // 执行SQL操作逻辑 } - 所有数字类型的字段(比如
tc_kimlik如果是数字类型)都要做类型验证,不要直接用Convert转换,防止格式错误。
内容的提问来源于stack exchange,提问作者erkan özdemir
相关产品推荐
相关产品推荐

