SQL INSERT INTO语句未将数据插入数据库

时间:2018-08-27 08:43:57

标签: sql-server vb.net insert-into

我无法找出此代码中的错误。但是,此insert into查询不会将数据提供给我的SQL Server数据库。

Try
    Dim connetionString As String
    Dim cnn As SqlConnection
    connetionString = "Data Source=LAPTOP-7I5LAV8T; Initial Catalog=dbTailorMadePeople; User ID=sa; Password=sa1111"
    cnn = New SqlConnection(connetionString)
    cnn.Open()
    Dim cmd As New SqlCommand With {.CommandText = "INSERT INTO rsMember(firstName, middleName, lastName, memberID) VALUES ('" & txtFirstName.Text & "', '" & txtMiddleName.Text & "', '" & txtLastName.Text & "', '" & txtID.Text & "')", .Connection = cnn}

    cmd.ExecuteNonQuery()

    MsgBox("Success")

Catch ex As Exception

End Try

2 个答案:

答案 0 :(得分:1)

由于您使用的是ADO.Net,请始终对查询进行参数设置,以避免SQL注入。

ex

Dim query as String = String.Empty
query &= "INSERT INTO rsMember(firstName, middleName, lastName, memberID)  "
query &= "VALUES (@firstName,@middleName, @lastName, @memberID)"

Using conn as New SqlConnection("yourConnectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@firstName", strFName)
            .Parameters.AddWithValue("@middleName", strMName)
            .Parameters.AddWithValue("@lastName", strLName)
            .Parameters.AddWithValue("@memberID", strMemberID)
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing 

答案 1 :(得分:-1)

此行有错误:

Dim cmd As New SqlCommand With {.CommandText = "INSERT INTO rsMember values (firstName, middleName, lastName, memberID) VALUES ('" & txtFirstName.Text & "', '" & txtMiddleName.Text & "', '" & txtLastName.Text & "', '" & txtID.Text & "')", .Connection = cnn}

注意:sql查询中缺少值

提示:1)在执行Sql查询之前,请将您的sql查询临时保存在字符串中。

Dim SqlQuery as string ="Your insert query"
Dim cmd As New SqlCommand With {.CommandText = SqlQuery  , .Connection = cnn}

2)在此行使用断点

将SqlQuery简化为字符串=“您的插入查询”

在运行时中断,从SqlQuery变量获取值并检查查询是否正常工作。