我有以下代码。我的问题是我无法在我的表中插入记录,当我运行代码时没有错误。代码有什么问题?
Dim Conn As SqlConnection
Dim cmd As SqlCommand
Dim ConString As String
ConString = "SERVER=MAXPAYNE-PC\DEVELOPER;DATABASE=sample;User=sa;Pwd=bwd"
Conn = New SqlConnection(ConString)
Try
Conn.Open()
For J As Integer = 0 To ListBox3.Items.Count - 1
cmd = New SqlCommand("INSERT INTO players (name) VALUES (" & ListBox3.Items(J).ToString & ")")
cmd.ExecuteNonQuery()
Next
Conn.Close()
Catch ex As Exception
End Try
答案 0 :(得分:2)
"当我运行代码时没有错误" 没有错误,因为你有一个空的catch。 Why are empty catch blocks a bad idea?
错误是命令没有分配连接。这应该有效:
cmd = New SqlCommand("INSERT INTO players (name) VALUES (" & ListBox3.Items(J).ToString & ")")
cmd.Connection = Conn
您还应该熟悉Using
- 语句并将其用于实现IDisposable
的所有对象,例如SqlConnection
,以确保它始终被置位/关闭(即使出错)
最后但并非最不重要:始终使用SQL-Parameters而不是字符串连接来阻止sql注入:
Using conn As New SqlConnection("SERVER=MAXPAYNE-PC\DEVELOPER;DATABASE=sample;User=sa;Pwd=bwd")
Dim sql = "INSERT INTO players (name) VALUES (@name)"
Using cmd As New SqlCommand(sql, conn)
Dim nameParameter = New SqlParameter("@name", SqlDbType.NVarChar)
cmd.Parameters.Add(nameParameter)
conn.Open()
For Each name As String In ListBox3.Items
cmd.Parameters("@name").Value = name
Try
Dim inserted As Int32 = cmd.ExecuteNonQuery()
Catch ex As Exception
' do something meaningful here (f.e. logging or at least output the error) '
' empty catches are evil in most cases since they conceal problems from you but not from the users '
Throw
End Try
Next
End Using
End Using ' conn.Close not needed due to the Using '