我无法构建代码,使我能够使用重复键更新 sql 语句将 gridview 数据插入 mysql 数据库。
网格视图只是一个普通的网格视图,它连接到浏览和上传按钮。这使我能够将 excel 电子表格上传到我的网格视图——它不是数据绑定的。
我已经在 VB 中完成了这项工作,但我发现在 vb.net 中编写它是一项艰巨的任务。这是VB中的代码。
Dim connectionString As String = "Server=*****;Database=****;Uid=****;Pwd=r*****;allow user variables=true"
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button2.Click
Dim i As Integer = 0
Dim student id,name,age,adress dbSQL_query As String
Dim dbSQL_cmd As New SqlClient.SqlCommand
Dim dbSQL_con As New SqlClient.SqlConnection
Using SQLConnection As New MySqlConnection(connectionString)
SQLConnection.Open()
For i = 0 To DataGridView1.RowCount - 1
Using sqlCommand As New MySqlCommand()
student id = DataGridView1.Item(0, i).Value.ToString
name = DataGridView1.Item(1, i).Value.ToString
age = DataGridView1.Item(2, i).Value.ToString
adress = DataGridView1.Item(3, i).Value.ToString.ToLower
dbSQL_query = "INSERT INTO student) VALUES (" + addQoute(student_id) + ", " + _
addQoute(name) + ", " + _
addQoute(age) + ", " + _
addQoute(adress) + ", " + _
addQoute(status) + ") on duplicate key update name=(" + addQoute(name) + "),age=(" + addQoute(age) + "),adress=(" + addQoute(adress) + ")"
With sqlCommand
.CommandText = dbSQL_query
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
sqlCommand.ExecuteNonQuery()
dbSQL_cmd = New SqlClient.SqlCommand(dbSQL_query, dbSQL_con)
End Using
Next
'MessageBox.Show(DataGridView1.RowCount & " student details has been inserted")
SQLConnection.Close()
End Using
End Sub
Public Function addQoute(ByVal str As String) As String
str = Trim(str)
Return "'" + str + "'"
End Function