当我试图将数据插入数据库时,会出现错误,称为“将数据类型varchar转换为数字时出错”
这是我的代码
objcon.DoExecute("INSERT INTO OrderItemF
VALUES('" & dgOrder.Item("Item No", i).Value & "'
,'"& dgOrder.Item("Item Type", i).Value & "'
,'" & txtOdrNo.Text & "'
,'" & dgOrder.Item("Unit Price", i).Value & "'
,'" & dgOrder.Item("Quantity", i).Value & "'
,'" & dgOrder.Item("Discount", i).Value & "'
,'" & dgOrder.Item("Total Value", i).Value &
"')"
)
我正在从名为dgorder的数据网格查看器中插入数据
答案 0 :(得分:1)
你的问题是在你做的时候
"'" & dgOrder.Item("Unit Price", i).Value & "'"
对于数字,您的查询看起来像'value'
。但是对于数字,你不需要单引号。因此,您需要做的是删除具有数值的单引号。
这是你的数据库抱怨 - “我希望整数,你给我一个字符串”
修改强>
我的原始答案解决了您的插入问题。现在,您需要对null
值,数据中可能的单引号以及将文本转换为null
进行更多的工作
dim itemNum as string = dgOrder.Item("Item No", i).Value ' assume it is string
itemNum = If(string.IsNullOrEmpty(itemNum), "NULL", "'" & itemNum.Replace("'", "''") & "'")
dim itemType as string = dgOrder.Item("Item Type", i).Value ' assume it is string
itemType = If(string.IsNullOrEmpty(itemType), "NULL", "'" & itemType.Replace("'", "''") & "'")
dim orderNum as string = If(string.IsNullOrEmpty(txtOrdNo.Text), "NULL", "'" & itemType.Replace("'", "''") & "'")
dim decVal as Decimal
dim intVal as Decimal
dim unitPrice as string = If(dgOrder.Item("Unit Price", i).Value, "") ' assume it is decimal
if Decimal.TryParse(unitPrice, decVal) Then
Throw New Exception("Invalid Unit Price")
Else
unitPrice = decVal.ToString()
End If
dim quantity as string = If(dgOrder.Item("Quantity", i).Value, "") ' assume it is integer
if Integer.TryParse(unitPrice, intcVal) Then
Throw New Exception("Invalid Quantity")
Else
quantity = intVal.ToString()
End If
dim discount as string = If(dgOrder.Item("Discount", i).Value, "0") ' assume it is decimal
if Decimal.TryParse(discount, decVal) Then
Throw New Exception("Invalid Discount")
Else
discount = decVal.ToString()
' may need: discount = If(decVal = 0, "NULL", decVal.ToString())
End If
dim total as string = If(dgOrder.Item("Total Value", i).Value, "") ' assume it is decimal
if Decimal.TryParse(total, decVal) Then
Throw New Exception("Invalid Total Value")
Else
total = decVal.ToString()
End If
dim sql as String = String.Format("INSERT INTO OrderItemF VALUES({0},{1},{2},{3},{4},{5},{6})",
itemNum, itemType, orderNum, unitPrice, quantity, discount, total)
objcon.DoExecute(sql)
这更像是编程