如何修复VB.NET代码中的“array bounds cannot appear in type specifiers”错误
VB.NET数据库插入代码错误修复方案
错误原因
你遇到的“array bounds cannot appear in type specifiers”错误,根源是创建SqlCommand对象时的语法错误:VB.NET中实例化对象必须使用New关键字,你直接把构造函数参数跟在SqlCommand类型后面,编译器会误以为你在声明数组,从而抛出这个错误。
另外原代码还有两个严重问题:
- 字符串拼接SQL语句存在SQL注入风险,同时会导致日期、特殊字符等格式错误
- 未正确释放数据库连接资源,可能造成连接泄漏
修复后的代码
' 使用Using语句自动释放连接和命令资源 Using con As New SqlConnection("Data Source=localhost;Initial Catalog=WebAssignment1;Integrated Security=True") con.Open() ' 使用参数化查询,避免SQL注入和格式问题 Dim sql As String = "Insert into List_Assignment (tid, task, customer, mandays, startDate, addDate, estimateDate, status, completionDate, remark, lastUpdate) values (@tid, @task, @customer, @mandays, @startDate, @addDate, @estimateDate, @status, @completionDate, @remark, @lastUpdate)" Using command As New SqlCommand(sql, con) ' 添加参数,注意参数类型要和数据库字段类型匹配 command.Parameters.AddWithValue("@tid", tid) command.Parameters.AddWithValue("@task", task) command.Parameters.AddWithValue("@customer", customer) command.Parameters.AddWithValue("@mandays", mandays) command.Parameters.AddWithValue("@startDate", startDate) command.Parameters.AddWithValue("@addDate", addDate) command.Parameters.AddWithValue("@estimateDate", estimateDate) command.Parameters.AddWithValue("@status", status) command.Parameters.AddWithValue("@completionDate", completionDate) command.Parameters.AddWithValue("@remark", remark) command.Parameters.AddWithValue("@lastUpdate", lastUpdate) command.ExecuteNonQuery() MessageBox.Show("Successfully Insert.") End Using End Using
关键修复点
- 给
SqlCommand实例化加上New关键字,修正语法错误:Dim command As New SqlCommand(...) - 替换字符串拼接为参数化查询:通过
@参数名占位符,再用Parameters.AddWithValue绑定参数,彻底避免SQL注入,同时解决日期、特殊字符的格式问题 - 使用
Using语句包裹SqlConnection和SqlCommand:确保对象使用后自动释放资源,避免连接池耗尽
内容的提问来源于stack exchange,提问作者Putu Widianingsih
相关产品推荐
相关产品推荐

