我目前正在尝试将代码插入到数据库中。
我有以下代码。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
Dim Con As SqlConnection
Dim cmd As New SqlCommand
Dim connstring As String
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Try
Con = New SqlConnection(connstring)
cmd = New SqlCommand("Insert into Rota ([Id],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday],[Sunday],[UserID]) Values('" & chosen & "','" & mon & "','" & tues & "','" & wed & "','" & thur & "','" & fri & "','" & sat & "','" & sun & "','" & user & "')", Con)
cmd.Connection.Open()
Dim rows As Integer = cmd.ExecuteNonQuery()
MsgBox(rows.ToString() & " rows affected")
MsgBox("done")
cmd = New SqlCommand("SELECT * from Rota", Con)
Dim rows2 As Integer = cmd.ExecuteNonQuery()
MsgBox(rows2.ToString() & " rows affected")
Catch ex As System.Data.SqlClient.SqlException
MsgBox(ex.Message)
End Try
End Sub
当我的代码执行时,它会返回并告诉我该行已受到影响。但是,如果我查看实际的数据库。它没有插入它!
答案 0 :(得分:0)
首先,您通过以下代码进行检查是错误的:
cmd = New SqlCommand("SELECT * from Rota", Con)
Dim rows2 As Integer = cmd.ExecuteNonQuery()
对于select
语句,您应该使用ExecuteReader()
或将其更改为Select count(*) as cn from ROTA
并通过ExecuteScalar()
其次,您需要运行Sql Profiler
并在第一个ExecuteNonQuery()
之后立即设置断点,然后查看Profiler
以确保您的命令正确且插入正确,然后无需进一步,在SQL Mamagenent Studio
运行SELECT * from Rota with(nolock)
并确保插入数据。然后继续运行您的应用程序然后运行此查询SELECT * from Rota
。如果在最后一个查询数据中没有,但在第一个查询中存在transaction rollback
问题,但如果两个记录都没有,则表示插入问题,如果两者都存在记录,您的查询申请效果不佳。