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

C#中遇System.Data.SqlClient.SqlException:varchar转bigint类型转换错误求助

问题:varchar转bigint数据类型转换错误

抛出异常:Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
附加信息:Error converting data type varchar to bigint

更新查询代码

private void btnUpdate_Click(object sender, EventArgs e)
{
    query = ("update items set name='" + txtName.Text + "',category='" + txtCategory.Text + "',price='" + txtPrice.Text + "where iid =" + id + "'");
    fn.setData(query);
    loadData();
    txtName.Clear();
    txtCategory.Clear();
    txtPrice.Clear();
}

数据操作方法代码

public void setData(String query)
{
    SqlConnection con = getConnection();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    con.Open();
    cmd.CommandText = query;
    cmd.ExecuteNonQuery();
    con.Close();

    MessageBox.Show("Data Processed Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

解决方法

核心问题分析

  1. SQL语法错误:字符串拼接时遗漏了必要的符号,导致SQL语句结构混乱,数据库解析时将错误的字符串内容尝试转换为bigint类型,触发错误。
  2. SQL注入风险:直接拼接用户输入到SQL语句中,不仅易出错,还存在严重的安全漏洞。

第一步:临时修复语法错误

你的拼接语句存在两处关键语法问题:

  • price='" + txtPrice.Text + "where 缺少闭合单引号和逗号,导致where被并入price的取值中
  • iid =" + id + "' 多了多余的单引号,bigint类型的字段值不需要用单引号包裹

修正后的拼接语句(仅临时解决语法问题,不推荐长期使用):

query = "update items set name='" + txtName.Text + "', category='" + txtCategory.Text + "', price=" + txtPrice.Text + " where iid = " + id;

注:如果price是字符串类型才需要加单引号,根据你的数据库表结构调整。


第二步:使用参数化查询彻底解决(强烈推荐)

参数化查询是解决类型转换错误、避免SQL注入的标准方案,重构代码如下:

重构更新按钮代码

private void btnUpdate_Click(object sender, EventArgs e)
{
    string query = "update items set name = @Name, category = @Category, price = @Price where iid = @Id";
    
    fn.setData(query, 
        new SqlParameter("@Name", txtName.Text),
        new SqlParameter("@Category", txtCategory.Text),
        new SqlParameter("@Price", Convert.ToDecimal(txtPrice.Text)), // 按数据库price字段类型转换,如int/decimal
        new SqlParameter("@Id", id));
    
    loadData();
    txtName.Clear();
    txtCategory.Clear();
    txtPrice.Clear();
}

重构数据操作方法setData

public void setData(string query, params SqlParameter[] parameters)
{
    using (SqlConnection con = getConnection()) // using自动释放连接,避免泄漏
    {
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddRange(parameters);
        con.Open();
        cmd.ExecuteNonQuery();
    }

    MessageBox.Show("Data Processed Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

补充注意事项

  • 确保参数类型与数据库字段类型严格匹配:比如price是decimal类型就用Convert.ToDecimal,iid是bigint则确保id变量为long或可转换的数值类型。
  • 始终使用using语句管理数据库连接,自动释放资源。
  • 禁止直接将用户输入拼接进SQL语句,参数化是必须遵循的规范。

内容的提问来源于stack exchange,提问作者16 jivrajani Isha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:09:17