sql-server 数据库INSERT未保存

rryofs0p  于 2022-10-31  发布在  其他
关注(0)|答案(1)|浏览(181)

我创建了一个名为addPeople()的函数,参数为firstname和lastname。当用户输入名字和姓氏并单击add按钮时,新的条目将添加到数据库中。但是,一旦程序重新启动,新添加的条目就消失了,并且没有保存。这是为什么呢?我如何才能真正保存新数据呢?

Sub addPeople(ByVal fname As String, ByVal lname As String)
        Dim conn As SqlConnection
        conn = New SqlConnection(getConnectionString)

        Dim cmd As New SqlCommand
        cmd.CommandType = CommandType.Text

        cmd.Connection = conn

        ' Open the connection '
        conn.Open()
        ' Start the "transaction" so the insert saves to the database '
        cmd.CommandText = "BEGIN TRANSACTION"
        cmd.ExecuteNonQuery()
        ' Insert the new data into the database '
        cmd.CommandText = "INSERT people (firstname, lastname) VALUES ('" + fname + "', '" + lname + "')"
        cmd.ExecuteNonQuery()
        ' Save the changes to the database '
        cmd.CommandText = "COMMIT"
        cmd.ExecuteNonQuery()
        ' Close the connection '
        conn.Close()
    End Sub

我已经尝试启动事务,然后使用COMMIT来确保保存更改,但仍然不起作用。
编辑:经过进一步的测试,我还注意到我的deletePeople()函数也没有完全保存对数据库的更改。
第一个

sbdsn5lh

sbdsn5lh1#

而不是这样:

cmd.CommandText = "BEGIN TRANSACTION"
cmd.ExecuteNonQuery()

您希望在连接上开始事务:

var transaction = connection.BeginTransaction()

都起来了:

using (var transaction = connection.BeginTransaction())
{
    cmd.CommandText = "INSERT people (firstname, lastname) VALUES ('" + fname + "', '" + lname + "')";
    cmd.Transaction = transaction;
    cmd.ExecuteNonQuery();
    transaction.Commit();
    //transaction.Rollback();
}

相关问题