简体   繁体   English

我的这个SQL Insert语句怎么了?

[英]What's wrong with this SQL Insert statement of mine?

I am trying to add a record to my table, however I'm getting an exception after it attempts to do so. 我正在尝试向表中添加一条记录,但是在尝试这样做后却遇到了异常。 I am able to open the connection successfully, (my first messagebox shows up) but after that I get the exception. 我能够成功打开连接(出现我的第一个消息框),但是之后我得到了异常。 Here's my code: 这是我的代码:

Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
    Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    con = New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;")
    Try
        cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
        cmd.Connection = con
        con.Open()
        MsgBox("Connection Open ! ")
        cmd.ExecuteNonQuery()
        MsgBox("Record inserted")
        con.Close()
    Catch ex As Exception
        MsgBox("Error!")
    End Try
End Sub

For future readers - Sql parameters will save a lot of your and your coworkers time. 对于将来的读者-Sql参数将节省您和您的同事很多时间。

Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
    Dim connString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;"
    Using connection As New SqlConnection(connString)
        Using command As New SqlCommand(connection)
            command.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (@FirstName, @Lastname)"
            Dim params As SqlParameter() =
            {
                New SqlParameter With { .ParameterName = "@FirstName", .SqlDbType.VarChar, .Value = txtFirstName.Text },
                New SqlParameter With { .ParameterName = "@LastName", .SqlDbType.VarChar, .Value = txtLastName.Text },
            }
            command.Parameters.AddRange(params)
            connection.Open() 
            command.ExecuteNonQuery()
            ' Inserted
        End Using
    End Using
End Sub 

Same for try.. catch (as @Plutonix has noticed in the comments) - if you will get "real" exception you will find reason and solution much faster 对于try.. catch也是如此(如@Plutonix在注释中所注意到的)-如果您将获得“真实”异常,则可以更快找到原因和解决方案

You need to look at the exception message (ex.Message) see what the issue is...If you have an error similar to multipart identifier then try this query string instead of your current query string for a quick test. 您需要查看异常消息(ex.Message)以了解问题所在...如果您遇到类似于multipart标识符的错误,请尝试使用此查询字符串而不是当前查询字符串进行快速测试。

    cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES ('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"

Check out parameterized query as previously indicated 如前所述签出参数化查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM