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() & ")"

那么有什么解决方案吗?

只填充表中可用字段的子集没有错,只要未填充的列被指定为可为null或已分配默认值(假设为SQL server)。

但是,构建命令的方式有问题:您没有在字符串值(即ccname)周围加引号,也没有防范SQL注入攻击。

使用参数化查询要好得多。

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

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...

最新更新