vb.net数据库查询值和目标字段的数量不相同

时间:2012-07-31 23:59:42

标签: vb.net

我有一个包含16个字段的数据库,我只想填写前7个字段。 我正在使用此命令

"INSERT INTO products (SupplierID, catalogid, ccode,cname,oprice,cprice,pother2) VALUES (" & reader("SupplierID").ToString() & "," & reader("catalogid").ToString() & "," & reader("ccode").ToString() & "," & reader("cname").ToString() & "," & reader("oprice").ToString() & "," & reader("cprice").ToString() & "," & reader("pother2").ToString() & ")"

所以任何解决方案?

1 个答案:

答案 0 :(得分:1)

仅填充表中可用字段的子集没有任何问题,只要您未填充的列被指定为可空或已分配默认值(假设为SQL服务器)。

但是,构建命令的方式有问题:您没有关于看起来像字符串值(即ccname)的引号,也没有防范SQL注入攻击。

最好使用parameterized query

粗略地说,您的代码看起来像:

Dim oCommand As New SqlCommand()

oCommand.Connection = oConnection

oCommand.CommandText = "INSERT INTO products (SupplierID, catalogid, ccode,cname,oprice,cprice,pother2) VALUES ("?, ?, ?, ?, ?, ?, ?)"

oCommand.Parameters(0).Value = reader("SupplierID")
oCommand.Parameters(0).Value = reader("catalogid")

etc...