【问题标题】:SqlCommand that inserts data has no effect [closed]插入数据的SqlCommand没有效果[关闭]
【发布时间】:2018-09-28 14:35:07
【问题描述】:

我正在尝试使用 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

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 另外,您不应包含任何递增的主键。
    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 2015-04-14
    • 2011-03-09
    • 2020-09-14
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多