我正在VB中创建一个更新Sub类,并使用insert而不是Query in Query,因为我想在一次运行中更新多个数据。
这是我在多个更新数据中的引用:SQL - Update multiple records in one query
但是当我运行它时会出现错误信息。
“在SQL语句结束时缺少分号(;)。”
但在我的查询结束时有一个分号。
这是我的查询:
Insert into IngredientStock(IngredientID,CategoryId,UnitID,IngredientName,Price)
values(46,2,1,'Beans', 100) ON DUPLICATE KEY
UPDATE
ingredientID= Values(IngredientID),
CategoryID = Values(CategoryID),
UnitID = Values(UnitID),
IngredientName = Values(IngredientName),
Price = values(Price);
这是我的更新子类
Sub UpdateInfo(ByVal table As String, ByVal PrimaryKey As String, ByVal C1 As String, ByVal C2 As String, ByVal C3 As String, ByVal C4 As String, ByVal Datas As String)
con.Close()
con.Open()
Query = "Insert into " & table & "(" & PrimaryKey & "," & C1 & "," & C2 & "," & C3 & "," & C4 & ") values (" & Datas & ") ON DUPLICATE KEY UPDATE " & PrimaryKey & "= Values(" & PrimaryKey & "), " & C1 & " = values(" & C1 & ")," & C2 & " = values(" & C2 & "), " & C3 & " = values(" & C3 & ")," & C4 & " = values(" & C4 & ");"
cmd = New OleDbCommand(Query, con)
DR = cmd.ExecuteScalar
con.Close()
End Sub
答案 0 :(得分:3)
首先,永远不要连接字符串来创建SQL查询。如果成分之类的东西包含特殊字符(例如Palmer's Condensed Milk
),则会失败。
SQL参数还保留数据类型 - 根据一个片段,只有一个项是字符串,但代码强制它们全部为文本。另外(最重要的)SQL参数避免SQL注入。
对于MySQL Upsert,你需要这样的东西:
Dim sql = <sql>
INSERT INTO SampleZ
(Id, Name, Country, Animal, Color, Price, ItemDate, Active)
VALUES
(@id, @n, @c, @a, @clr, @p, @dt, @act)
ON DUPLICATE KEY UPDATE
Name=@n, Country=@c,
Animal=@a, Color=@clr, Price=@p,
ItemDate=@dt, Active=@act
WHERE id = @id
</sql>.Value
Using dbcon As New MySqlConnection(connStr)
Using cmd As New MySqlCommand(sql, dbcon)
cmd.Parameters.Add("@id", MySqlDbType.Int32).Value = thisID
If thisID = -1 Then
cmd.Parameters("@id").Value = DBNull.Value
End If
cmd.Parameters.Add("@n", MySqlDbType.String).Value = TextBox1.Text
cmd.Parameters.Add("@c", MySqlDbType.String).Value = ComboBox1.Text
cmd.Parameters.Add("@a", MySqlDbType.String).Value = TextBox2.Text
cmd.Parameters.Add("@clr", MySqlDbType.String).Value = TextBox3.Text
cmd.Parameters.Add("@p", MySqlDbType.Decimal).Value = NumericUpDown1.Value
cmd.Parameters.Add("@dt", MySqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("@act", MySqlDbType.Bit).Value = chkActive.Checked
dbcon.Open()
Dim rows = cmd.ExecuteNonQuery()
End Using
End Using
重要说明:
MySqlDbType.DateTime
Using
块确保DbCOnnection和DbCommand对象正确关闭并在最后处置,以便应用程序不会泄漏资源答案 1 :(得分:0)