select from Mysql and put into variable VB.NET - mysql

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.

Related

Using 'Else' in While data.Read() does not work?

What I want to happen is if, textbox3.Text does not equal data(0) value then I want the MsgBox("test") to trigger. However, it does not. If the value of textbox3 does not exist with data(0) I want MsgBox("test") to trigger. I've tried every variation I could think of and I cannot get it to work.
Right now, if textbox.Text does not equal data(0) value nothing happens. However, if textbox3.Text equals data(0) then both Label3.Text = data(1) and MsgBox("Join code has been applied.") work.
Dim conn As New MySqlConnection
conn.ConnectionString = "server=;userid=;password=;database="
conn.Open()
Dim sqlquery As String = "SELECT * FROM joincodes WHERE code = '" & TextBox3.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If TextBox3.Text = data(0) Then
Label3.Text = data(1)
MsgBox("Join code has been applied.")
Else
MsgBox("test")
End If
End If
End While
There are a few things that need to be changed in the code.
Database connections have "unmanaged resources" associated with them, which means that you have to .Dispose() of them when you have finished using them. To avoid some fiddly code, VB.NET conveniently provides the Using statement.
It is best to give controls meaningful names because it is much easier to see what is going on in the code. E.g. if you accidentally typed TextBox37 when you meant TextBox87 it would be hard to see, but you wouldn't mistype tbUserName for tbFavouriteColour.
In MySQL, CODE is a keyword, so you need to escape it with backticks to be safe: MySQL Keywords and Reserved Words
Putting variables directly into SQL statements is generally a mistake. SQL parameters are used for doing that; they are easy to use and prevent a lot of problems.
If you are relying on the order of the columns from a database query (e.g. data(0)) then you must specify that order in the query (e.g. SELECT `col1`, `col2` FROM joincodes) because if you use * then they could be returned in any order.
You are probably only interested in the first returned value from the database (if there is a returned value), so I added the ORDER BY `col1` LIMIT 1.
Always use Option Strict On. It will save you time.
With regard to the question as asked, all you need to do is have a flag, I used a boolean variable named success, to indicate if things went right.
I also added some points indicated with 'TODO: in the following code which you'll need to take care of to make sure it works properly:
Option Infer On
Option Strict On
Imports MySql.Data.MySqlClient
' ... (other code) ... '
'TODO: Any type conversion from the string TextBox3.Text.'
'TODO: Give TextBox3 a meaningful name.'
Dim userCode = TextBox3.Text
Dim connStr = "your connection string"
Using conn As New MySqlConnection(connStr)
'TODO: Use the correct column names.'
Dim sql = "SELECT `col1`, `col2` FROM `joincodes` WHERE `code` = #code ORDER BY `col1` LIMIT 1"
Using sqlCmd As New MySqlCommand(sql, conn)
'TODO: Use correct MySqlDbType and change .Size if applicable.'
sqlCmd.Parameters.Add(New MySqlParameter With {.ParameterName = "#code", .MySqlDbType = MySqlDbType.String, .Size = 24, .Value = userCode})
Dim success = False
Dim rdr = sqlCmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
'TODO: Change GetString to the appropriate Get<whatever>.'
If rdr.GetString(0) = userCode Then
success = True
'TODO: Check that `col2` is a string - change the GetString call as required and call .ToString() on the result if needed.'
Label3.Text = rdr.GetString(1)
MessageBox.Show("Join code has been applied.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
If Not success Then
MsgBox("test")
End If
End Using
End Using

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

MySQL inserting a column into a variable

I'm working on a project that needs to prevent double username inserted in a database my code looks like this:
Command = New MySqlCommand("Select * From userscanner", Connection)
Command.ExecuteNonQuery()
Dim dr As MySqlDataReader
dr = Command.ExecuteReader
With dr
.Read()
Dim check As String = .Item(1)
.Close()
If check = txtbox_username.Text Then
MsgBox("Username Already Taken")
Exit Sub
My problem is it only gets 1 column or is there any other way to prevent double username in my database?
I need all column in my username column. I'm using VB and MySQL.
You should ask your database if a particular user name exists or not.
This could be done with a WHERE clause
Dim sqlText = "SELECT 1 FROM userscanner WHERE username = #name"
Using Command = New MySqlCommand(sqlText, Connection)
Command.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtbox_username.Text
Dim result = Command.ExecuteScalar()
if result IsNot Nothing Then
MsgBox("Username Already Taken")
End If
End Using
Here I assume that your database table named userscanner has a field named username (the field retrieved by your code with Item(1)) where you store the user names. Adding a WHERE condition and a simple return of 1 if there is a record allows to use the simple ExecuteScalar that returns the value 1 if there is a matching record to your textbox value or Nothing if there is no record
I found an answer to the question on my own.
Command = New MySqlCommand("Select * From userscanner WHERE Username = '" & txtbox_username.Text & "'", Connection)
Command.ExecuteNonQuery()
Dim dr As MySqlDataReader
dr = Command.ExecuteReader
dr.Read()
dr.Close()
If dr.HasRows Then
MsgBox("Username Already Taken")
Thanks for the help guys

Deleting ID from MySQL database

I am trying to delete the users username from the database when s/he logs out. My code is the following which doesn't work. I Think it may have something to do with the connection string (database, password thing)
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Query As String
Dim con As MySqlConnection = New MySqlConnection("Server=localhost;User ID=root;Password=*Mypassword*;Database=myusers")
con.Open()
Query = "Delete FROM users WHERE name =" + loginuser.Text
'Table = users
'Name = Varchar(20)
'loginuser.text = Name (username)
Dim cmd As MySqlCommand = New MySqlCommand(Query, con)
MsgBox(Query)
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
MsgBox("Record is Successfully Deleted")
Else
MsgBox("Record is not Deleted")
End If
con.Close()
End Sub
You are not enclosing name value with quotes in your sql string,
Ex: Delete FROM users WHERE name = 'abcname'
Change your code to use parameters which is clean and secure way to pass values and you don't have to worry about quotes when working with string parameters
Query = "Delete FROM users WHERE name = #name"
Dim cmd As MySqlCommand = New MySqlCommand(Query, con)
MySqlCommand.Parameters.AddWithValue("#name",loginuser.Text)
String literals need to be enclosed in single quotes so your query should be:
Query = "Delete FROM users WHERE name = '" + loginuser.Text + "'"
Also concatenating a string into a SQL statement opens you up to SQL injection attacks (or even just think about someone putting "O'Brien" as the login name). You should always use parameters instead.

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 & "'"