我有一个Mysql数据库设置:
表帐户:
Id:1
姓名:Donny
积分:600
我有一个名为Buy的按钮 点击后运行以下
If credits.Text <= 0 Then
MsgBox("Geen credits meer.")
Else
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server=xxx;port=3306; user id=xxx; password=xxx; database=xxx"
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("error connecting to database")
End Try
Dim myadapter As New MySqlDataAdapter
Dim sqlquery = "UPDATE account SET credits = credits -700 WHERE id='" & Trim(id.Text) & "'"
Dim mycommand As New MySqlCommand()
mycommand.Connection = conn
mycommand.CommandText = sqlquery
myadapter.SelectCommand = mycommand
mycommand.ExecuteNonQuery()
Try
conn.Close()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
Finally
conn.Dispose()
End Try
End If
例如,我的帐户有600个学分。而且我想买一个价格为700的产品。系统说不可能,因为你只有600个学分。当前代码显示-100个学分,但我如何检查并显示错误消息?
答案 0 :(得分:1)
您只需在程序中添加一项功能,即可检查是否有足够的积分:
Public Function checkCredits(ByVal creditsNeeded As Int32, ByVal id As String) As Boolean
Dim conn As New MySqlConnection
conn.ConnectionString = "server=xxx;port=3306; user id=xxx; password=xxx; database=xxx"
conn.Open()
Dim mycommand As New MySqlCommand()
With mycommand
.Connection = conn
.CommandType = CommandType.Text
.CommandText = "SELECT credits FROM account WHERE id = @id"
.Parameters.Add("@id", MySqlDbType.VarChar).Value = id
End With
Dim creditsAvailable As Int32 = mycommand.ExecuteScalar
conn.Close()
If creditsAvailable >= creditsNeeded Then
Return True
Else
Return False
End If
End Function
然后调整上面的代码以使用它:
If credits.Text <= 0 Then
MsgBox("Geen credits meer.")
Else
If checkCredits(700, id.Text) Then
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server=xxx;port=3306; user id=xxx; password=xxx; database=xxx"
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("error connecting to database")
End Try
Dim myadapter As New MySqlDataAdapter
Dim sqlquery = "UPDATE account SET credits = credits -700 WHERE id='" & Trim(id.Text) & "'"
Dim mycommand As New MySqlCommand()
mycommand.Connection = conn
mycommand.CommandText = sqlquery
myadapter.SelectCommand = mycommand
mycommand.ExecuteNonQuery()
Try
conn.Close()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
Finally
conn.Dispose()
End Try
Else
MessageBox.Show("Not Enough Credits")
End If
End If