我使用以下代码使用MySql
DataTable
表格
Function DB_Multi_Ins_Or_Upd_From_DT(ByVal dt As DataTable, ByVal DestTbl$) As Integer
Using SQLConnection As New MySqlConnection(CnStr)
Using sqlCommand As New MySqlCommand()
Dim CmdTxt$ = "INSERT INTO " & DestTbl & " ("
For Each Col As DataColumn In dt.Columns
CmdTxt &= Col.ColumnName & ", "
Next
CmdTxt = CmdTxt.Substring(0, CmdTxt.Length - 2) & ") VALUES ("
For x As Integer = 0 To dt.Rows.Count - 1
For xx As Integer = 0 To dt.Columns.Count - 1
CmdTxt &= "@" & "R" & x.ToString & "C" & xx.ToString & ", "
sqlCommand.Parameters.AddWithValue _
("@" & "R" & x.ToString & "C" & xx.ToString, dt.Rows(x)(xx))
Next xx
CmdTxt = CmdTxt.Substring(0, CmdTxt.Length - 2) & "), ("
Next x
CmdTxt = CmdTxt.Substring(0, CmdTxt.Length - 3)
CmdTxt &= " ON DUPLICATE KEY UPDATE "
For Each Col As DataColumn In dt.Columns
CmdTxt &= Col.ColumnName & "=VALUES(" & Col.ColumnName & "), "
Next
CmdTxt = CmdTxt.Substring(0, CmdTxt.Length - 2)
With sqlCommand
.CommandText = CmdTxt
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Dim AffRows% = sqlCommand.ExecuteNonQuery()
Return AffRows
Catch ex As MySqlException
Return -1
Finally
SQLConnection.Close()
End Try
End Using
End Using
End Function
代码更新1行但返回2。
编辑:似乎仅在update
上返回了错误的结果,而在insert
上返回了正确数量的受影响的行
出了什么问题?如何修复并获得受影响的行数?
编辑:要测试我需要的代码:
1)导入MySql.Data.MySqlClient
2)给
cnstr
之类的值 "数据源=" + Server_Name +&#34 ;; username =" + UserDB +&#34 ;;密码=" +密码+&#34 ;;数据库=" + Database_Name +""3)创建一个
DataTable
,其列名如DB表的字段4)调用传递DataTable的函数和表的名称 在DB上
答案 0 :(得分:0)
来自Microsoft
当插入或更新的表上存在触发器时,(ExecuteNonQuery的)返回值包括插入或更新操作影响的行数以及受触发器或触发器影响的行数
因此,要么重复计算受影响的行,要么实际更新2行。
答案 1 :(得分:0)
如果ON DUPLICATE KEY UPDATE,则每行的受影响行值为1 该行将作为新行插入,如果更新现有行,则为2 如果现有行设置为其当前值
,则为0