Update inventory when sale is made vb.net - mysql

I have a SalesForm whereby a user can add their sales. In my inventory table I have total tires, quantity in stock, and quantity sold. I know I have duplicate fields (total tires and quantity in stock), but only the quantity in stock will be used for updating and total tires will be used for referring to check how much they have sold out and which ones are being sold out fast.
What I am trying to do is after I click on save on SalesForm to add new sales, the inventory table should also be updated. The quantity in stock and quantity sold should add how much sold from the sales form and get saved to inventory.
But the calculation isn't working. I see the same information after the update.
This is the code for update:
Public Sub updatestock()
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=golden_star"
Dim a As Integer
' Dim total, onstock, quantity As String
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
' Dim Sda As MySqlDataAdapter
a = Val(txtStock.Text) - Val(ComboBox3.Text)
'total = txtStock.Text
'quantity = ComboBox3.Text
'onstock = total - quantity
Query = "update inventory set quantity_onstock = '" & a & "' where brand = '" & ComboName.Text & "' and size = '" & ComboSize.Text & "' "
Command = New MySqlCommand(Query, MysqlConn)
MessageBox.Show("Stock Updated Successfully")
READER = Command.ExecuteReader
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
Screenshot frontend:
Screenshot database as it saves the same number it doesn't do the calculation:
Then I pasted the method name updatestock() on button click after clicking on save, but it's not working. Can anybody correct me with the update statement?

Here is a MUCH better way to structure the query code:
Public Sub UpdateStock(newQty As Integer, brand As String, size As String)
Dim SQL As String = "UPDATE Inventory SET quantity_onstock = #Qty WHERE brand = #Brand AND size = #Size;"
Using cn As New MySqlConnection("server=localhost;userid=root;password=****;database=golden_star"), _
cmd As New MySqlCommand(SQL, cn)
cmd.Parameters.AddWithValue("#Qty", newQty)
cmd.Parameters.AddWithValue("#Brand", brand)
cmd.Parameters.AddWithValue("#Size", size)
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Note the Using block, the query parameters, the function arguments instead of form controls, and the lack of error handling or messaging. The method is concerned with running the query and ONLY running the query. You should adopt these changes for ALL your queries. Also note the use of ExecuteNonQuery() instead of ExecuteReader().
What this means is you also need to change the code that calls the function. It will need to handle the messages and errors, and provide the parameter arguments.
Whether this fixes your issue is hard to say.
As a further step from here, you can then start moving these SQL methods into their own module, away from any forms code, to create meaningful separation of concerns.

Related

Checking if the fund is sufficient

I am currently doing an ATM Management System, I want my program to check if the amount entered does not exceed the account's balance on database. Here is my code:
Dim w As Double
w = Val(txtwithdraw.Text)
adapter = New MySql.Data.MySqlClient.MySqlDataAdapter("SELECT `balance` FROM `jaagbank` WHERE
acctnum = '" & Form1.namebox.Text & "'", con)
dtable.Clear()
adapter.Fill(dtable)
If w > dtable.Rows.Count Then
MsgBox("Insufficient Balance")
txtwithdraw.Clear()
Return
End If
Decimal is a good datatype to used for money. Don't use the vb6 Val(). You can get unexpected results. Put Option Strict and Option Infer on. I used .TryParse to test the input in txtwithdraw. If it returns True, it puts the converted decimal value in WithdrawalAmount.
Keep your data objects local to the method where they are used. Connections and commands need to be closed and disposed. Using...End Using blocks handle this for us even if there is an error.
Always use parameters to avoid sql injection. If the code is running in Form1, do not qualify namebox with Form1. It seems a bit strange that a field named acctnum is not a number but a String containing a name. You will need to check your database for the correct datatype and field size. I had to guess.
Since you are retrieving a single piece of data, you can use .ExecuteScalar which will give you the first column of the first row.
Private Sub OPCode()
Dim WithdrawalAmount As Decimal
If Not Decimal.TryParse(txtwithdraw.Text, WithdrawalAmount) Then
MessageBox.Show("Please enter a valid withdrawal amount.")
Return
End If
Dim Balance As Object
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand("SELECT `balance` FROM `jaagbank` WHERE acctnum = #Name;", con)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar, 100).Value = Form1.namebox.Text
con.Open()
Balance = cmd.ExecuteScalar
End Using
If Balance Is Nothing Then
MessageBox.Show("Account not recognized.")
Return
End If
If WithdrawalAmount > CDec(Balance) Then
MsgBox("Insufficient Balance")
txtwithdraw.Clear()
Return
End If
End Sub

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

2nd query fails to run

I'm new to programming and I have a problem with the following code. The 2nd query is not running. It should insert all the data in the first database to the other database.
MySQLConn = New MySqlConnection
MySQLConn.ConnectionString = Connection
Adapter = New MySqlDataAdapter
Dim QRY = "SELECT EquipmentID, Quantity FROM subdbborroweq"
Dim EQID As Integer
Dim QTY As Integer
Dim TimeAndDate As String = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Try
MySQLConn.Open()
Command = New MySqlCommand(QRY, MySQLConn)
Reader = Command.ExecuteReader
While Reader.Read()
EQID = Reader(0)
QTY = Reader(1)
Dim QRY1 = "INSERT INTO borrowlogs( `BorrowerName`, `EquipmentID`, `Quantity`, `TimeDate`) VALUES (" &
AddBorrower.TextBox1.Text & "," & EQID & ", " & QTY & "," &
TimeAndDate & ")"
Command = New MySqlCommand(QRY1, MySQLConn)
End While
MySQLConn.Close()
I have put together some code but please note this is untested as I don't use MySQL anymore.
Instead of a MySqlDataReader I've used a DataTable as I find them a little easier to work with but that is preference. I've also implement Using for the MySqlConnection and MySqlCommand objects. This is so the objects are disposed of properly and you don't have to worry about do that.
Please note that I don't know your data structure. I have taken a guess of what the MySqlDbTypes are. You may have to change. I would suggest however saving TimeDate as just that, a DateTime.
You may also want to implement a little further checking for DBNulls on row(0) and row(1). I've left this to you to look at, it may not be necessary but it's always worth looking into as they do cause problems when the crop up.
I'm unsure how you want to handle multiple rows in your DataTable brought back from the SELECT statement. So what I am doing is looping through the Rows collection. If you don't want to and you simply want the first row, you can change the SELECT statement to only bring back the first row which I believe is done using LIMIT. This would mean your statement would look something like SELECT EquipmentID, Quantity FROM subdbborroweq LIMIT 1. You may want to look at a filter using WHERE and you may want to consider ordering your data using ORDER BY. Alternatively remove the For Each row loop and use Integer.TryParse(dt.Rows(0).Item(0).ToString(), EQID)
This is the code I have put together. It may not be 100% but hopefully it will give you something to go on:
Dim dt As New DataTable
Using con As New MySqlConnection(Connection),
cmd As New MySQLCommand("SELECT EquipmentID, Quantity FROM subdbborroweq", con)
con.open()
dt.Load(cmd.ExecuteReader)
If dt.Rows.Count > 0 Then
cmd.CommandText = "INSERT INTO borrowlogs(BorrowerName, EquipmentID, Quantity, TimeDate) VALUES (#Uname, #EQID, #QTY, #TAD)"
cmd.Parameters.Add("#Uname", MySqlDbType.VarChar)
cmd.Parameters.Add("#EQID", MySqlDbType.Int32)
cmd.Parameters.Add("#QTY", MySqlDbType.Int32)
cmd.Parameters.Add("#TAD", MySqlDbType.DateTime)
For Each row As DataRow In dt.Rows
cmd.Parameters("#Uname").Value = AddBorrower.TextBox1.Text
cmd.Parameters("#EQID").Value = row.Field(Of Int32)(0)
cmd.Parameters("#QTY").Value = row.Field(Of Int32)(1)
cmd.Parameters("#TAD").Value = DateTime.Now
cmd.ExecuteNonQuery()
Next
End If
End Using
Dont you need ' in your string values? VALUES ('John',
$QRY1 = "INSERT INTO borrowlogs( BorrowerName, EquipmentID, Quantity, TimeDate) VALUES ('" & AddBorrower.TextBox1.Text & "','" & EQID...

'Like' statement not producing any results

I have a products table where I am trying to search for a value a user enters via a textbox to get a products description, basically any product that might contain the word 'Bread' for example,and the results will be displayed in a combobox, yet my select statement yields no results. When i run the exact same query in access it shows the information so I am not sure if my issue in my code is with the syntax of my query,can someone maybe advise what I am doing wrong here please. I'm using MS Access, and vb.net 2010.
Sub search_prod(ByVal cmb As ComboBox, ByVal searchval As String)
searchval = Trim("'*" & searchval & "*'")
con.Open()
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select (Products.Product_Descr) From [Products] WHERE (Product_Descr LIKE " & searchval & ")"
Dim dr As OleDbDataReader = cmd.ExecuteReader
Do While dr.Read
cmb.Items.Add(dr.GetString(0))
Loop
con.Close()
End Sub

Visual Basic 2010 - Display multiple MySql queries to different datagridviews on a Form

Good day,
I'm developing a project where I use Visual Basic 2010 and MySql. The function of the project is to perform sports timing services. I'm semi-knowledgeable with programming in the above environments, and when I struggle, I Google for answers and it serves me well 99% of the time.
My problem is this: I have a database with tables for each sports event. All the data gets captured and all the functionality is working as intended. I would now like to display the results of this race on a Form using four GridViews (4 is the most race distances that are allowed). These results need to be separately displayed (using different queries) for each race distance (4 at most).
I have code to display the results, but this populates all four gridviews with the same data. Here is my code:
Private Sub ListResults()
Dim query As String = "SELECT RaceNo, FirstName, LastName, RaceDistance, RaceTime FROM " & frmMain.EventCode & _
" WHERE NOT ISNULL(RaceTime) AND RaceDistance = '" & frmMain.RaceDistance1 & "' ORDER BY RaceDistance ASC, RaceTime ASC;"
Dim connection As New MySqlConnection(frmMain.connStr)
Dim da As New MySqlDataAdapter(query, connection)
Dim ds As New DataSet
Try
If da.Fill(ds) Then
dgvLoadResultsA.DataSource = ds.Tables(0)
dgvLoadResultsB.DataSource = ds.Tables(0)
dgvLoadResultsC.DataSource = ds.Tables(0)
dgvLoadResultsD.DataSource = ds.Tables(0)
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
da = Nothing
connection.Close()
connection = Nothing
End Try
End Sub
I understand that I need to produce four different queries (which I'm able to do), but I'm not sure how to send the results of those queries to the different gridviews. I don't seem to fully understand how to send the result of my queries to different tables in the dataset. I can just create the code by running the sub with different parameters and variables, but thought that there is a better way of doing this.
Any assistance in this matter would be highly appreciated.
Thank you in advance.
What you need to do is use a different DataSet per Query.
Personally I'd split your Query code into a separate Function taking the Event and Distance as Parameters and returning your DataTable;
Private Function GetResults(ByVal EventCode As Integer, ByVal RaceDistance As Integer) As DataTable
Dim query As String = "SELECT RaceNo, FirstName, LastName,
RaceDistance, RaceTime
FROM " & EventCode & _
" WHERE NOT ISNULL(RaceTime)
AND RaceDistance = '" & RaceDistance & "'
ORDER BY RaceDistance ASC, RaceTime ASC;"
Dim connection As New MySqlConnection(frmMain.connStr)
Dim da As New MySqlDataAdapter(query, connection)
Dim ds As New DataSet
Try
If da.Fill(ds) Then
Return ds.Tables(0)
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
da = Nothing
connection.Close()
connection = Nothing
End Try
End Sub
I've assumed your Data Types here, you will of course need to modify this to use the correct Data Types.
Then you can attach your DataSources using;
dgvLoadResultsA.DataSource = GetResults(EventCodeA, RaceDistanceA)
dgvLoadResultsB.DataSource = GetResults(EventCodeB, RaceDistanceB)
dgvLoadResultsC.DataSource = GetResults(EventCodeC, RaceDistanceC)
dgvLoadResultsD.DataSource = GetResults(EventCodeD, RaceDistanceD)
Ideally you'd also pass in your Connection String to the GetResults Function, then your Function is Unit Testable, but I'll leave that decision to you.
Of course, you should ideally check that your Function returns a valid DataTable before attaching. But I didn't want to over complicate the solution!