I don't know what's the real problem since there are no error being reported. So what I want these codes to do is insert a transaction record to the database but there is nothing being returned. Here are the codes that related to this:
MainForm
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim payment As New Payment
payment.Show()
AddHandler payment.PaymentEvent, AddressOf paymentSuccess
payment.PaymentAmount = TransactionTotal
End Sub
Public Sub paymentSuccess(ByVal sender As Object, ByVal e As Payment.PaymentMadeEventArgs)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "select * from inventory"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
Dim itId As Integer = reader.GetString("itemid")
Dim itName As String = reader.GetString("itemname")
If e.PaymentSuccess = True Then
paymentSuccessQuery(itId, itName)
End If
End While
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) VALUES('" & itemid & "', '" & itemname & "')"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
If reader.Read Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Transactionform
Public Class Payment
Public Delegate Sub PaymentMadeEvent(ByVal sender As Object, ByVal e As PaymentMadeEventArgs)
Public Event PaymentEvent As PaymentMadeEvent
Private _paymentAmount As Decimal
Public Property PaymentAmount As Decimal
Get
Return _paymentAmount
End Get
Set(ByVal value As Decimal)
_paymentAmount = value
AmountBox.Text = String.Format("{0:c}", _paymentAmount)
End Set
End Property
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim total As Decimal = 0
Try
total = Decimal.Parse(AmountBox.Text.TrimStart("₱")) - Decimal.Parse(PaymentBox.Text)
Catch
MessageBox.Show("Error Occured, please enter a valid amount!")
Return
End Try
If (total > 0) Then
AmountBox.Text = total.ToString()
Else
MessageBox.Show("Please give " + String.Format("{0:c}", -total))
RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() With {.PaymentSuccess = True})
End If
End Sub
Public Class PaymentMadeEventArgs
Inherits EventArgs
Private _paymentSuccess As Boolean
Public Property PaymentSuccess As Boolean
Get
Return _paymentSuccess
End Get
Set(ByVal value As Boolean)
_paymentSuccess = value
End Set
End Property
End Class
End Class
ExecuteReader executes the command (the insert) but it has been built to return the rows extracted by a SELECT command.
Calling Read to discover if your INSERT has been successful is meaningless in this context.
You should call ExecuteNonQuery, catch the return value, and if it is not equal to zero, then you have inserted the record.
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
Using mydbcon = New MySqlConnection("server=localhost;userid=root;password=;database=sdudb"
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) " & _
"VALUES(#id, #name)"
Using COMMAND = New MySqlCommand(Query, mydbcon)
COMMAND.Parameters.Add("#id", MySqlDbType.VarChar).Value = itemid
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = itemname
Dim rowsAdded = COMMAND.ExecuteNonQuery()
if rowsAdded = 0 Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Notice also the I have changed your code to use the appropriate Using statement around the disposable objects like the connection and the command and, of utmost importante, I have changed your query to use a more safe parameterized query approach (not sure about the MySqlDbType for the ID parameter, it seems to be an integer but in your original query you put it between single quotes like a string)
Related
I am trying to display value in combobox using MySQL in vb.net. Right now the problem that I am facing is that combobox is not displaying values from MySQL. I have the below code:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
However, using the above code Combobox1.Text returns nothing but if I use below code which has a different query it works:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("Name")
ComboBox1.Items.Add(sName)
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Could someone please check and let me know what could be the issue? Thanks!
so the highlights as i mentioned them in the comments
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' You need only to open aconnection once
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "db connection successful"
'First load both Combobox
Dim query As String
query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sname = READER.GetString("name")
ComboBox1.Items.Add(sname)
ComboBox2.Items.Add(sname)
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Closing
Try
MySqlConn.Close()
MySqlConn.Dispose()
Catch ex As Exception
End Try
End Sub
ANd now the Comboboxes
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'Only when there is a item selected , ask for data
If ComboBox1.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label11.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
This is exactly as i described on Form_load you fill both comboboxes
When you now change one of the comboxes one of the label change too.
Sometimes you have to update the Element to see a change
in that case you write at the end of the loop
Label10.Update()
Starting at the top...
Keep your database objects local to the method where they are used. (Not Form level variables) You can make the connection string a class level string variable. This is the only way you can ensure that they are closed and disposed.
Using...End Using blocks will close and dispose your database objects even if there is an error. The constructor of the connection takes the connection string. Connections are precious objects. Don't open the connection until directly before the .Execute method and close it as soon as possible.
It doesn't make much sense that the user could select an item from ComboBox1 before the Form.Load.
In general, we don't want to download anymore data than necessary and we want to hit the database as little as possible. In the Form.Load we bind the combobox to a data table that contains the name and price fields, setting the display and value members. Now, whenever the user picks a name in the combo we can retrieve the price without connecting to the database again.
I noticed that you were using Val in another event. This is an old VB6 method that can give you unexpected results. .Net and vb.net have all sorts of ways to get numbers out of strings that are faster and more reliable. CInt, .TryParse, .Parse, CType, Convert.To etc.
Public Class Form1
Private ConString As String = "server=localhost;userid=root;password=root;database=s974_db"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Fill combobox
Dim dt As New DataTable
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("select Name, Price from processors;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using 'Closes and disposes both connection and command
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Price"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Label10.Text = ComboBox1.SelectedValue.ToString
ClearLabels()
End Sub
Private Sub ClearLabels()
Label11.Text = ""
Label12.Text = ""
Label13.Text = ""
Label14.Text = ""
Label15.Text = ""
Label16.Text = ""
Label17.Text = ""
Label18.Text = ""
Label19.Text = ""
Label20.Text = ""
End Sub
End Class
I have a simple form with a button and 2 textbox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection(ConfigurationManager.ConnectionStrings("db.My.MySettings.dbConnectionString").ToString)
Try
'MysqlConn.Dispose()
'MysqlConn.Close()
MysqlConn.Open()
Dim str As String
str = "SELECT substring_index(substring(path,1,locate(substring_index(path,'\\',-1),path)-2),'\\',-1)as PATH FROM foto where id_product = '" & TextBox2.Text & "'"
Dim dbCommand As New MySqlCommand(str, MysqlConn)
Dim dbReader = dbCommand.ExecuteReader
While dbReader.Read()
If IsDBNull(dbReader(0)) OrElse String.IsNullOrEmpty(dbReader.GetString(0)) Then
TextBox1.Text = "0"
Else
TextBox1.Text = dbReader.Item("PATH")
End If
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
when i put in textbox2 "1" i have my desired value.
But when i put "2", this id_product dont exist, i dont have "0".
It's blank and Textbox1 has my previous value.
What i do wrong ??
If the query doesn't return any record, your code doesn't enter the while loop (dbReader.Read return false) and thus you don't set the textbox to "0" but you should also start to use parameterized queries. It is very important to avoid possible parsing errors and mainly to avoid Sql Injection attacks
So, you could test if your query has produced any record verifying the property HasRows of the DataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using MysqlConn = New MySqlConnection(ConfigurationManager.ConnectionStrings("db.My.MySettings.dbConnectionString").ToString)
Try
MysqlConn.Open()
Dim str As String
str = "SELECT substring_index
(substring(path,1,
locate(substring_index(path,'\\',-1),path)-2),
'\\',-1) as PATH
FROM foto where id_product = #pid"
Dim dbCommand As New MySqlCommand(str, MysqlConn)
dbCommand.Parameters.Add("#pid", MySqlDbType.VarChar).Value = textBox2.Text
Using dbReader = dbCommand.ExecuteReader
if dbReader.HasRows Then
While dbReader.Read()
If IsDBNull(dbReader(0)) OrElse String.IsNullOrEmpty(dbReader.GetString(0)) Then
TextBox1.Text = "0"
Else
TextBox1.Text = dbReader.Item("PATH")
End If
End While
else
TextBox1.Text = "0"
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
I want to add the ages of all the employees in MySQL database column(using sum query) and then want to display its result(the value)on the click of a button in VB in a textbox.I have given a try but its not working.I am not able to figure this out.Please help....Image
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim Mysqlconn As New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"
Try
Mysqlconn.Open()
command.Connection = Mysqlconn
command.CommandText = "select sum(age) from data.etable"
Dim sqlresult As Object
sqlresult = command.ExecuteScalar
Dim str As String
str = sqlresult
TextBox5.Text = str
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
a demo on standard port 3306 for Mysql
Schema
create table etable
( eid int auto_increment primary key,
age int not null
);
insert etable(age) values (1),(2),(3);
VB Code
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
' Perform a connection test, and save ConnectionString
' in Module-level variable "conn"
Dim dbname As String = "dbname"
Dim hostname As String = "hostname"
Dim user As String = "dbuser"
Dim password As String = "password"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
Try
conn.Open()
MsgBox("Connection Test Successful")
' and ConnectionString set for subsequent queries
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close() ' close connection for now
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
connect()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iAgeSum As Integer
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
TextBox1.Text = "junk"
Else
iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
TextBox1.Text = iAgeSum
End If
conn.Close()
End Sub
End Class
Screenshot
i have a code but it's not working. i was trying to put a value in label2 but it's not working. please help me.
Private Sub student_no_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles student_no.Click
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = sample;"
Dim READER As MySqlDataReader
Try
MySqlConnection.Open()
Dim query As String
query = " select id from sample.student where last_name = '" & txtlastname.Text & "' "
Dim Command As New MySqlCommand(query, MySqlConnection)
READER = Command.ExecuteReader
Label2.Text = query.ToString
MessageBox.Show("Student Number Generated")
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
You are using .ToString on query, which is a string. What you should be doing is operations on the READER object.
Since SELECT will always return a list of results, you have to treat the results as such, like...
While READER.Read()
MessageBox.Show((READER.GetInt32(0)))
End While
.Read() returns the next element in the returned rowset
If READER.Read() Then
Label2.Text = READER.GetString(0)
End If
in ths program my DISPLAY and ADD button is working but at the time of UPDATE and DELETE record it gives the exception error i.e CHECK THE MANUAL THAT CORRESPONDS TO YOUR MYSQL SERVER FOR THE RIGHT SYNTAX.....
can you please correct my syntax...?
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class _Default Inherits System.Web.UI.Page
Dim connection As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Dim mydataset As New DataSet()
Dim mydataadpter As MySqlDataAdapter = New MySqlDataAdapter()
Public query As String
' Dim con As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
connection.Open()
End Sub
Protected Sub btn_display_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_display.Click
Dim mysql As MySqlCommand = New MySqlCommand("select * from userinfo", connection)
mydataadpter.SelectCommand = mysql
mydataadpter.Fill(mydataset, "product")
Try
GridView1.DataSource = mydataset
GridView1.DataBind()
GridView1.DataMember = "product"
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add.Click
query = "INSERT INTO userinfo VALUES("
query = query + txt_userid.Text + ",'" + txt_username.Text + "'," + txt_age.Text + ")"
Dim MySqlCommand = New MySqlCommand(query, connection)
Dim i As Integer = MySqlCommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is saved")
Else
MsgBox("record is not saved")
End If
End Sub
Protected Sub btn_update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_update.Click
Try
query = "UPDATE USERINFO SET username='" + txt_username.Text + "',"
query = query + "age=" + txt_age.Text
query = query + "WHERE userid=" + txt_userid.Text
Dim mysqlcommand = New MySqlCommand(query, connection)
MsgBox(query)
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is updated")
Else
MsgBox("record is not updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_delete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_delete.Click
Try
query = "DELETE FROM userinfo WHERER userid=" + txt_userid.Text
Dim mysqlcommand As New MySqlCommand(query, connection)
MsgBox(query)
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is deleted")
Else
MsgBox("record is not deleted")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Your query seems to be syntactically correct, however, I would always use a parameterized query instead of a string concatenation. This will avoid Sql Injection and the quoting around the parameter value will be carried out by the framework code.
Try this for the update method
Try
query = "UPDATE USERINFO SET username=#uname, age=#uage WHERE userid = #uid";
Dim mysqlcommand = New MySqlCommand(query, connection)
mysqlcommand.Parameters.AddWithValue("#uname", txt_username.Text))
mysqlcommand.Parameters.AddWithValue("#uage",Convert.ToInt32(txt_age.Text))
mysqlcommand.Parameters.AddWithValue("#uid",Convert.ToInt32(txt_userid.Text))
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is updated")
Else
MsgBox("record is not updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Another important thing to fix in your code is the global connection object. Don't do that. If one of your query fails for whatever reason you leave the connection open and that is a serious problem for the stability of your code.
Try
query = "UPDATE USERINFO SET username=#uname, age=#uage WHERE userid = #uid";
Using con = new MySqlConnection(.......)
Using cmd = new MySqlCommand(query, con)
con.Open()
cmd.Parameters.AddWithValue(......)
End Using
End Using
Catch ex As Exception
....
End Try
The using statement is critical to ensure a correct usage of expensive resources like a connection to the database and ensure a proper close and dispose of these kind of objects