【问题标题】:Insert Values Into Database using ListBox使用 ListBox 将值插入数据库
【发布时间】:2015-02-08 08:24:15
【问题描述】:

我有以下代码。我的问题是我无法在表中插入记录,并且当我运行代码时没有错误。代码有什么问题?

    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

【问题讨论】:

  • 你怎么知道没有错误?您有一个空的 Catch 块,因此您只是忽略了可能引发的任何异常。在Catch 块中放入一些代码,如果抛出异常,它将实际通知您,然后您实际上可以判断是否发生错误。如果你在这种情况下运行代码没有收到任何通知,那么你可以说没有发生错误。

标签: sql-server vb.net sql-server-2005 listbox


【解决方案1】:

“当我运行代码时没有错误”没有错误,因为你有一个空的 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-statement 并将其用于所有实现IDisposable 的对象,例如SqlConnection,以确保它始终被释放/关闭(即使出现错误)。

最后但同样重要的是:始终使用 SQL 参数而不是字符串连接来防止 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 '

【讨论】:

  • 我是编程新手,请耐心等待
  • @user3916571:不客气。请注意,我已编辑我的答案以提供示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
相关资源
最近更新 更多