2nd query fails to run - mysql

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...

Related

Update inventory when sale is made vb.net

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.

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

Need help filling datagrid from MySQL

I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try
You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).

select from Mysql and put into variable VB.NET

I have a problem with the following piece of code:
dim nama as string
cnn.ConnectionString = "Server=localhost; user id=root; password=; database=aplikasi_store_testing;"
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "SELECT ID_Barang, Nama_Barang from data_barang WHERE ID_Barang= '" & txtIDBarangInput.Text & "';"
Afterwards, I would need to change the data from "Nama_Barang" to nama.
Could anyone help me with this? In advance, thank you very much for your precious help!
Probably you need to execute your command
dim nama as string
cnn.ConnectionString = "............"
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "SELECT ID_Barang, Nama_Barang from data_barang WHERE ID_Barang= #id"
cmd.Parameters.AddWithValue("#id", txtIDBarangInput.Text )
Dim reader = cmd.ExecuteReader()
while reader.Read()
nama = reader(1).ToString()
End While
Of course this code assumes that you have already declared the connection and the command object.
Note also that I have removed your string concatenation and placed a parameter placeholder.
This is the right thing to do when you build strings to pass to the database engine.
Read about this subject (Sql Injection)
By the way, selecting back the value of ID_Barang that you already know is useless.
Also, on this field, I have a doubt. In your question code you put the value between single quotes treating the value as a string. But the name ID_Barang suggest a numeric value. Are you sure that this field is a text?
cmd.CommandText = "SELECT Nama_Barang from data_barang WHERE ID_Barang = '" & txtIDBarangInput.Text & "';"
Dim o As Object = cmd.ExecuteScalar()
If (Not o.Equals(DBNull.Value)) Then
nama = DirectCast(o, string)
Else
name = string.Empty
End If
You should use parameters rather than inserting the id value directly into the query string to avoid sql injection vulnerabilities etc.

MySQL Data NOT Deleting from table VB.NET

Why won't this delete the data in my MySQL database!?
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Try
dbCon = New MySqlConnection("Server=Localhost;Database=myusers;Uid=root;Pwd=Mypassword")
strQuery = "DELETE settings FROM settings WHERE user=" & Me.loginuser.Text
'* FROM settings WHERE user = "Testuser"'
SQLCmd = New MySqlCommand(strQuery, dbCon)
' OPEN THE DB AND KICKOFF THE QUERY
dbCon.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
req1.Text = "" And exlink.Text = ""
End While
' DONE! Close DB
DR.Close()
dbCon.Close()
Catch ex As Exception
TextBox8.Text = ("Fail" & vbCrLf & vbCrLf & ex.Message)
End Try
Here is a picture of my database:
Alternatively I could somehow make it replace what is already in the database, in which case please help me with that.
Try
strQuery = "DELETE FROM settings " _
& " WHERE user = '" & Me.loginuser.Text & "'"
but as was stated earlier, you should be using parameterized queries. If you had a user named O'Brien then your query (as composed above) would fail because of the embedded single quote. When you use DELETE, you are deleting entire records and you already specify the table name in the FROM clause.
I will try to change your code in this way
Using con = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText = "DELETE * FROM settings WHERE user = #ulogin"
Using cmd = new MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", Me.loginuser.Text)
cmd.ExecuteNonQuery()
End Using
End Using
First and foremost, do not use string concatenation to create command texts to pass to the database engine. In that way you risk Sql Injections, also, if the user name contains a single quote (i.e. O'Hara) your code will fail with a syntax error (Same problems arise for date formatting, parsing numeric decimals and other globalization issues). Instead a parametrized query like the one in code above will avoid all of these problems.
In a parametrized query, the text of the query doesn't contains the actual value for the search condition or the update or insert data. Instead it contains placeholders ( in our case it is called #ulogin). The correct value to insert at the placeholders position is specified using one or more MySqlParameter added to the Parameters collection of the MySqlCommand. In this case I have used the AddWithValue method that derives the correct datatype directly from the datatype of the value. Because Me.loginuser.Text is a string value then the parameter will be treated as a string value replacing incorrect single quotes and removing extraneus characters usually used to Mount Sql Injections Attacks. The engine will do the rest inserting the correct value at the placeholder at execution time
EDIT: Seeing your comment about the MySql connector used, I will try to update my answer to show a semi-equivalent version for NET 1.
Try
Dim con As MySqlConnection = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText as String = "DELETE * FROM settings WHERE user = #ulogin"
Dim cmd As MySqlCommand = new MySqlCommand(sqlText, con)
Dim par As MySqlParameter = New MySqlParameter("#ulogin", MySqlDbType.VarChar)
par.Value = Me.loginuser.Text
cmd.Parameters.Add(par)
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
I am not sure if the connector 1.0.10 supports the parameter name with the # prefix or just the : prefix
i dont think you can use double quotes in mysql, i think its single quotes only. try
Query = "DELETE * FROM settings WHERE user = '" & Me.loginuser.Text & "'"