MySQL inserting a column into a variable - mysql

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

Related

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

Update multiple rows in mysql?

I need to know to to update more than one rows in database using vb.net.
In my database it have 3 rows (have id for each other ) and on my vb.net I have 3 text boxes. I need to update data using those 3 text boxes in one shot.
here is my vb.net code
MysqlConn.Open()
Dim Query As String
Query = "update cs set subject=#subject, place=#place where=#id"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Data Saved")
MysqlConn.Close()
You need to pass parameters
Dim sql as String = "update cs set subject=#subject, place=#place where id=#id" ' NOTE: id = #id
cmd = New MySqlCommand(sql, MysqlConn)
cmd.Parameters.addWithValue("#subject", txtSubject.Text)
cmd.Parameters.addWithValue("#place", txtPlace.Text)
cmd.Parameters.addWithValue("#id", CInt(txtId.Text)) ' id is int , I hope
' instead of reader do ExecuteNonQuery
Dim ret = cmd.ExecuteNonQuery()
MessageBox.Show("Success: " & (ret > 0).ToString())
You can also do ExecuteReader but you do that when you return something. I don't know MySql but in Sql Server you can use Output with Insert and Update. And you can use ExecuteReader to get this output.

Select statement have got error in VB.Net with mysql

The error message is also available in another threads but in my case it's different.
Object reference not set to an instance of an object. When querying the following select statement. What is the problem inside?
Dim con As New MySqlConnection(ConString)
Dim sql As String
Dim idno As Integer
sql = "select client_id from car_rent where car_id = #carid"
cmd.Parameters.AddWithValue("#carid", carid.Text.Trim)
cmd = New MySqlCommand(sql, con)
idno = cmd.ExecuteScalar()
If (idno > 0) Then
MsgBox("The Car is already Rented!", MsgBoxStyle.Exclamation, "Car Rental System")
Return
End If
I don't see you opening the connection anywhere. use
con.open()
Switch the order of these two lines
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("#carid", carid.Text.Trim)
Also the line in which you execute the command seems to be working because you are using Option Strict Off, and I suggest to change to Option Strict On. In the short term you have to solve many problems but it allows better coding practices
idno = CType(cmd.ExecuteScalar(), Integer)
However, if the command above doesn't find any record matching the parameter passed, ExecuteScalar returns Nothing and so you need to test for this situation
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
idno = CType(result, Integer)
And, of course, the connection should be opened before, so summarizing everything
Dim sql = "select client_id from car_rent where car_id = #carid"
Using con As New MySqlConnection(ConString)
Using cmd = New MySqlCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#carid", carid.Text.Trim)
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim idno = CType(result, Integer)
If (idno > 0) Then
MsgBox("The Car is already Rented!", MsgBoxStyle.Exclamation, "Car Rental System")
Return
End If
End If
End Using
End Using
Well probably is enough to test for Nothing on the result of ExecuteScalar to take your decision unless you need the idno variable for other purposes.

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.

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.