有谁知道如何修复此代码并使其正常工作?我想更新我的数据库,它将获得Combo box
中的值。是否可以在DB中同时更新1个或更多值?
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
提前致谢!!
答案 0 :(得分:0)
首先,您应该使用sql-parameters而不是字符串连接来防止可能的sql注入。
此外,如果有多个记录具有相同的yearLevel
,则您的代码已经更新了多个记录。
Dim sql = "UPDATE tblStudent SET course = @course,section = @section WHERE yearLevel = @yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("@course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("@course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("@course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
请注意,我并不知道列的数据类型,因此请相应地进行修改。我只想告诉你,首先使用正确的类型非常重要。
答案 1 :(得分:0)
这是'INSERTING',但是,它可以很容易地适应'更新':
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
您已声明field1
,并为其指定了Combobox2.SelectedValue
等