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

WPF应用向多表插入数据时抛出SqlException错误求助

问题解决

你的报错是SQL语法错误,根源在第二个插入语句的SQL文本里:

原代码中cmd2的SQL语句:

SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(@ViestiID,@Viesti2,@Viestinlahettaja", conn);

这里的values部分最后缺少一个右括号,导致SQL解析时在@Viestinlahettaja附近出错。

另外还有一个潜在的可读性问题:参数@Viesti2对应表字段Viesti,建议参数名和字段名保持一致(比如改成@Viesti),避免后续维护混淆。

修正后的cmd2代码:

SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(@ViestiID,@Viesti,@Viestinlahettaja)", conn);

cmd2.Parameters.AddWithValue("@ViestiID", txtbox_ID.Text);
cmd2.Parameters.AddWithValue("@Viesti", txtbox_Viesti.Text);
cmd2.Parameters.AddWithValue("@Viestinlahettaja", txtbox_Nimi.Text);

额外优化建议:

  • 使用using语句自动管理数据库连接和命令的释放,避免资源泄漏:
using (SqlConnection conn = new SqlConnection(@"Data Source=MYCOMPUTER\SQLEXPRESS;Initial Catalog=LomakeDB;User ID=***;Password=***"))
{
    conn.Open();
    // 执行cmd1和cmd2的代码放在这里
}
  • 尽量避免使用AddWithValue,它可能导致类型推断问题,推荐使用Add指定参数类型:
cmd1.Parameters.Add("@ID", SqlDbType.VarChar).Value = txtbox_ID.Text;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:05:16