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

C#操作SQL插入时Text转Int报错,求有效解决办法

问题描述

执行SQL插入bookData表操作时,代码中标记报错的位置出现整数转换错误,代码如下:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con1 = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=libralyServer;Integrated Security=True");
    con1.Open();             
    SqlCommand cmd1 = new SqlCommand("insert into bookData values(@bookName,@bookWriter,@bookTotel)", con1);
    cmd1.Parameters.AddWithValue("@bookName", textBox1.Text);
    cmd1.Parameters.AddWithValue("@bookWriter", textBox2.Text);
    cmd1.Parameters.AddWithValue("@bookTotel",int.Parse(textBox2.Text));//have error
    cmd1.ExecuteNonQuery();
    con1.Close();
}
修复方案
  • 修正输入框引用错误:核心错误是你把存储作者名的textBox2当成了书籍数量的输入源,应该替换为对应数量的输入框(比如textBox3,请根据你的实际UI控件命名调整)。
  • 使用安全的整数转换方法:int.Parse在输入非数字文本时会直接抛出异常,改用int.TryParse可以优雅处理转换失败的情况,同时给用户明确提示。
  • 优化数据库连接管理:用using语句包裹数据库连接和命令对象,确保资源自动释放,避免手动关闭连接可能导致的连接泄漏问题。

修正后的完整代码:

private void button1_Click(object sender, EventArgs e)
{
    // 验证数量输入是否合法
    if (!int.TryParse(textBox3.Text, out int bookTotal))
    {
        MessageBox.Show("请输入有效的书籍数量(数字格式)");
        return;
    }

    // 使用using自动释放数据库资源
    string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=libralyServer;Integrated Security=True";
    using (SqlConnection con1 = new SqlConnection(connectionString))
    {
        con1.Open();             
        using (SqlCommand cmd1 = new SqlCommand("INSERT INTO bookData (bookName, bookWriter, bookTotel) VALUES (@bookName, @bookWriter, @bookTotel)", con1))
        {
            cmd1.Parameters.AddWithValue("@bookName", textBox1.Text);
            cmd1.Parameters.AddWithValue("@bookWriter", textBox2.Text);
            cmd1.Parameters.AddWithValue("@bookTotel", bookTotal);
            cmd1.ExecuteNonQuery();
        }
    }

    MessageBox.Show("书籍信息插入成功");
}

额外提示:SQL语句中显式指定要插入的列名(如INSERT INTO bookData (bookName, bookWriter, bookTotel)...),可以避免因表结构变动导致的插入失败问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:50:35