How to read a value from mysql database? - mysql

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

Related

How to display data from mysql base from Dropdownlist selection

i want to display mysql data base from the dropdownlist. i populate data from dropdownlist using this code and it works perfectly. in this code it will show the productnames in the dropdownlist
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT tbl_productid,tbl_productname FROM tbl_products")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
cmbProducts.DataSource = cmd.ExecuteReader()
cmbProducts.DataTextField = "tbl_productname"
cmbProducts.DataValueField = "tbl_productid"
cmbProducts.DataBind()
con.Close()
End Using
End Using
cmbProducts.Items.Insert(0, New ListItem("Select Product"))
End If
Now base from the selected product name i want to display its productID to textbox. but this code gives me no output? i dont know what is wrong with my code anyone who can help me
This is code
Protected Sub cmbProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cmbProducts.SelectedIndexChanged
'MsgBox("Hellow World!", MsgBoxStyle.Critical)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim con As New MySqlConnection(constr)
con.Open()
Dim cmd As New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '" + cmbProducts.Text + "'", con)
Dim sda As New MySqlDataAdapter(cmd)
'Dim dr As New MySqlDataReader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read Then
txtProductID.Text = dr.GetValue(0)
End If
con.Close()
con.Dispose()
End Sub
Ok, a few things.
The drop list has two columns. data value (id), and data text.
What you have looks good.
However, when you get/grab/use the drop list, then you have this:
DropDownList1.Text - this will return the data value (1st column)
DropDownList1.SelectedValue - this will ALSO return data value (1st column)
DropDownList1.SelectedItem.Text - this gets the 2nd display text value (2nd column)
So, because a LOT of drop lists can be only one column, then the .text and .SelectedValue can both be used. (in other words, you can use .text, but it gets the first value, and since a lot of drop lists might only have one column, then .text always gets that first value). But I would consider the habit of SelectedValue for the column that drives the drop list.
In your case, you really do want the 2nd column, and thus you want to use:
DropDownList1.SelectedItem.Text
So,
New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '"
+ cmbProducts.SelectedItem.Text + "'", con)
I used my own data to demonstrate. Also I used given control names in my test program. This is not what your want to do in your application. Your control names are good.
I broke the code into the data access part and the user interface code. There is very little code in the actual event procedure.
You have set the .DataValueField to the id so you can retrieve that value in the SelectedIndexChanged event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillDropDownList()
End If
End Sub
Private Sub FillDropDownList()
Dim dt = GetListBoxData()
DropDownList1.DataTextField = "Name"
DropDownList1.DataValueField = "ID"
DropDownList1.DataSource = dt
DropDownList1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim dt = New DataTable
Dim Query = "Select Top 10 ID, Name
FROM Coffees;"
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(Query, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
TextBox1.Text = DropDownList1.SelectedValue
End Sub
There is no need to make a second round trip to the database. You already have the data you require.

Parameterize SQL Queries

I want parameterize some SQL Statements so my code isn't vunerable to SQL Injections any longer But i have actually no plan how to parameterize for example a where clause.
Dim accID As String = DatabaseConnecter.readField("SELECT ID FROM accounts WHERE accountname ='" & user & "' AND password='" & pw & "';")
The Problem is if you type in a given username, for example test and extend the username with. You can log in without entering the password into the Application.
Edit:
Public Function readField(ByVal sql As String) As String
Dim output As String = "ERROR"
Using cn = New MySqlConnection(connString.ToString())
Using cmd = New MySqlCommand(sql, cn)
cn.Open()
Using rd = cmd.ExecuteReader()
Try
rd.Read()
output = rd.GetString(0)
rd.Close()
Catch ex As Exception
End Try
End Using
cn.Close()
End Using
End Using
Return output
End Function
ยดยดยด
To have a parameterized query you need to create parameters and write a proper SQL text where, in place of values typed directly from your user, you have parameter placeholders.
So, for example, you sql text should be something like this
Dim sqlText = "SELECT ID FROM accounts WHERE accountname =#name AND password=#pwd"
Now you have a parameterized text, but stil we need to create the parameters that will be sent to the database engine together with your sql command.
You can create the parameter (two in this case) in this way before calling the method that executes the query
Dim p1 as MySqlParameter = new MySqlParameter("#name", MySqlDbType.VarChar)
p1.Value = user
Dim p2 as MySqlParameter = new MySqlParameter("#pwd", MySqlDbType.VarChar)
p2.Value = password
Dim pms As List(Of MySqlParameter) = new List(Of MySqlParameter)()
pms.Add(p1)
pms.Add(p2)
Now we need to pass this list to your method (and this requires changes to your method signature)
DatabaseConnecter.readField(sqlText, pms)
The method itself should change to something like
Public Function readField(ByVal sql As String, Optional pms As List(Of MySqlParameter) = Nothing) As String
Dim output As String = "ERROR"
Using cn = New MySqlConnection(connString.ToString())
Using cmd = New MySqlCommand(sql, cn)
cn.Open()
' This block adds the parameter defined by the caller to the command
' The parameters are optional so we need to check if we have really received the list or not
if pms IsNot Nothing Then
cmd.Parameters.AddRange(pms.ToArray())
End If
Using rd = cmd.ExecuteReader()
Try
rd.Read()
output = rd.GetString(0)
rd.Close()
Catch ex As Exception
End Try
End Using
' no need to close when inside a using block
' cn.Close()
End Using
End Using
Return output
End Function
The method now has an optional parameter that will contain the list of the parameters required by the query (or nothing if your query doesn't require parameters). This list is added to the command parameters collection and the query is now executed.
Final Note: Storing passwords in clear text into a database is a well known security problem. I suggest you to search about how to store passwords in a database.
Private Function GetID(User As String, pw As String) As String
Using cmd As New SqlCommand("SELECT ID FROM accounts WHERE accountname =#user AND password=#password", New SqlConnection(SQLConnString))
cmd.Parameters.AddWithValue("#user", User)
cmd.Parameters.Add("#password", SqlDbType.NVarChar)
cmd.Parameters("#password").Value = pw
Try
cmd.Connection.Open()
Return cmd.ExecuteScalar()
Catch ex As Exception
'handle error
Return Nothing
Finally
cmd.Connection.Close()
End Try
End Using
End Function
I've demostrated two methods of setting the parameters. Search for more info or comparison.

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.

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

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.