C#.NET项目执行SQL INSERT插入数据报无效列名错误如何解决
问题原因
你当前的报错是因为拼接SQL语句时,字符串类型的插入值没有用单引号包裹,SQL解析器会把未加单引号的字符串识别为列名而非插入的字段值,所以才会抛出Invalid column_name的错误。
临时修复方案(不推荐,仅用于快速验证)
如果直接改拼接写法,给字符串值前后加单引号即可:
SqlCommand sc1 = new SqlCommand("insert into tempdivcustcount(dist_name,dist_code,cust_count,year) Values('"+dist_name[i]+"','"+dist_code[i]+"',"+cust_count[i]+","+int.Parse(thresholdYear.Text)+") ", con);
注意:这种直接拼接用户输入的写法存在严重的SQL注入风险,且如果插入的字符串本身包含单引号时还会再次触发语法错误,绝对不建议在生产环境使用。
推荐修复方案(参数化查询)
用参数化的方式传递插入值,既可以避免SQL注入,也不需要手动处理单引号等特殊字符的转义,修正后代码如下:
// 先把年份提前解析,避免循环里重复解析 int year = int.Parse(thresholdYear.Text); // 用using自动释放数据库连接资源,避免连接泄漏 using (SqlConnection con = new SqlConnection(_connectionString)) { con.Open(); // 循环外提前创建命令对象,复用提升性能 SqlCommand sc1 = new SqlCommand(@" insert into tempdivcustcount(dist_name,dist_code,cust_count,year) Values(@dist_name, @dist_code, @cust_count, @year)", con); // 提前添加参数,指定和数据库对应的字段类型,循环内只修改参数值 sc1.Parameters.Add("@dist_name", SqlDbType.VarChar, 50); // 长度和数据库实际字段长度对应 sc1.Parameters.Add("@dist_code", SqlDbType.VarChar, 2); sc1.Parameters.Add("@cust_count", SqlDbType.Int); sc1.Parameters.Add("@year", SqlDbType.Int); for (int i = 0; i < dist_name.Length; i++) { sc1.Parameters["@dist_name"].Value = dist_name[i]; sc1.Parameters["@dist_code"].Value = dist_code[i]; sc1.Parameters["@cust_count"].Value = cust_count[i]; sc1.Parameters["@year"].Value = year; sc1.ExecuteNonQuery(); } }
额外注意事项
你当前代码中三个数组的长度不一致:dist_name长度为15,cust_count和dist_code长度为16,循环时会触发索引越界错误,需要核对数据补齐长度。
内容的提问来源于stack exchange,提问作者Jitender Singh
相关产品推荐
相关产品推荐

