插入数据的SqlCommand无效

时间:2018-09-28 14:35:08

标签: sql-server vb.net ado.net sqlcommand

我正在尝试使用VB.NET 2017将数据插入到现有的Microsoft SQL Server 2014表中。代码没有给我任何错误,但也没有插入记录。现在,我只想把它放到改变数据的地方,而不必担心用户输入。任何帮助表示赞赏。

我的猜测是它没有正确连接到SQL Server。

Imports System.Data.SqlClient
Public Class Form2

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sqlstr As String
    Dim connectionString As String = "server=localhost;database= database1;Trusted_Connection=True;"
    sqlstr = "Insert into tblname (id, gender) VALUES ([5], ['Bob'])"
    Try
        Using connection As New SqlConnection(connectionString)
            connection.Open()
            Dim cmdInsert As New SqlCommand(sqlstr, connection)
            connection.Close()
        End Using
        MsgBox("anything")    'this is just to see if it even runs
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

1 个答案:

答案 0 :(得分:4)

创建SqlCommand之后,只需调用ExecuteNonQuery即可运行SQL语句:

Dim cmdInsert As New SqlCommand(sqlstr, connection)
cmdInsert.ExecuteNonQuery()
connection.Close()

但是请注意,您的INSERT语句中的值不应 用方括号括起来:

sqlstr = "Insert into tblname (id, gender) VALUES (5, 'Bob')"