我正在使用此代码插入数据库,但每次插入多行时,问题是什么?
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Sub
答案 0 :(得分:4)
您是否检查过您的代码块是否被多次调用?一个快速的方法是在里面放一个警报框,这样你就可以计算它运行的次数。
答案 1 :(得分:2)
嗯......有很多问题。第一个是SQL注入的潜力,您应该使用命名参数。另一个是关于Dim com As New...
的行也应该在Using
子句中。
然而,该位代码中没有任何内容表明它正在插入超过1条记录。我建议你在ExecuteNonQuery
行上设一个断点,看看发生了什么。
答案 2 :(得分:0)
我已经检查并按下按钮点击执行了两次,我已经将代码更改为这个并且它已经解决了,但我不知道为什么click事件被执行了两次:
Dim i As Boolean = True
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
con.Open()
Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
If i = True Then
com.ExecuteScalar()
i = False
End If
End Using
con.Close()
End Using
End Sub