我正在用Access数据库做VB,我想创建一个按钮。哪个保存按钮检查尝试插入的数据在哪里重复或不与我的数据库进行比较。
这是我的代码,问题是我输入的内容只是显示用户已经存在。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
If (ComboBox2.Text = "") And (ComboBox3.Text = "")
And (TextBox3.Text = "") And (ComboBox4.Text = "")
Then
MsgBox("Please fill-up all fields!")
Else
Dim theQuery As String = ("SELECT * FROM Table1
WHERE"" [Subject_Code]=@Subject_Code ,[Day]=@Day,
[Times]=@Times , [Lecture]=@Lecture and [Class_Room]=@Class_Room""")
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, MyConn)
cmd1.Parameters.AddWithValue("@Subject_Code", TextBox6.Text)
cmd1.Parameters.AddWithValue("@Day", ComboBox2.Text)
cmd1.Parameters.AddWithValue("@Times", ComboBox3.Text)
cmd1.Parameters.AddWithValue("@Lecture", TextBox3.Text)
cmd1.Parameters.AddWithValue("@Class_Room", ComboBox4.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'User already exists
MsgBox("User Already Exist!")
Else
Dim Update As String = "INSERT INTO [Table1]
([Subject_Code], [Subject],
[Day], [Times], [Level],[Semester], [Lecture],[Class], [Class_Room])
VALUES (?,?,?,?,?,?,?,?,?)"
Using cmd = New OleDbCommand(Update, MyConn)
cmd.Parameters.AddWithValue("@p1", TextBox6.Text)
cmd.Parameters.AddWithValue("@p2", TextBox1.Text)
cmd.Parameters.AddWithValue("@p3", ComboBox2.Text)
cmd.Parameters.AddWithValue("@p4", ComboBox3.Text)
cmd.Parameters.AddWithValue("@p5", ComboBox1.Text)
cmd.Parameters.AddWithValue("@p6", ComboBox6.Text)
cmd.Parameters.AddWithValue("@p7", TextBox3.Text)
cmd.Parameters.AddWithValue("@p8", ComboBox5.Text)
cmd.Parameters.AddWithValue("@p9", ComboBox4.Text)
MsgBox("New Data Is Saved")
cmd.ExecuteNonQuery()
End Using
End If
End Using
End If
答案 0 :(得分:1)
首先快速浏览一下你的theQuery变量,它可能只是在你输入SO的地方出错了,但如果没有尝试:
Dim theQuery As String = "SELECT * FROM Table1 " &
"WHERE [Subject_Code] = @Subject_Code " &
"AND [Day] = @Day " &
"AND [Times] = @Times " &
"AND [Lecture] = @Lecture " &
"AND [Class_Room] = @Class_Room"
您对现有用户的检查基于5个字段,新数据的插入有9个字段。在不知道业务案例的情况下,我无法确定这是否正确,或者缺少的4个字段对检查是否真正重要并导致返回意外行。
我个人接下来的步骤是: