Select statement have got error in VB.Net with mysql - 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.

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

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

Hide part of String.Format within a ComboBox.Item

Is it possible to hide part of String.Format?
This my code:
'Select Product'
Try
MysqlConn.Close()
MysqlConn.Open()
Dim Query As String
Query = "select id, name,id_maker, id_types from product ORDER BY name ASC"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("name")
Dim sMaker = READER.GetString("id_maker")
Dim sTypes = READER.GetString("id_types")
Dim sId = READER.GetString("id")
'ComboBox1.Items.Add(sName)'
ComboBox1.Items.Add(String.Format("{0}|{1}|{2}|{3}", sName, sMaker, sTypes, sId))
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
'Select Product'
I want to hide {3} which is sId in the ComboBox, because later I need to use a query where the ComboBox1.Text is used and the id is necessary.
Maybe you could change the way you are assigning the data to the ComboBox.
First thing to do is change the query and use CONCAT:
SELECT id, CONCAT(name,'|',id_maker,'|',id_types) AS value FROM product ORDER BY name ASC
I would also implement Using:
Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.
You also don't need the READER. Instead load the data into a DataTable and assign that to the .DataSource property on the ComboBox.
Your code would look something like this:
Using con As New MySqlConnection(connectionString)
cmd As New MySqlCommand("SELECT id, CONCAT(name,'|',id_maker,'|',id_types) AS value FROM product ORDER BY name ASC", con)
con.Open()
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "value"
ComboBox1.ValueMember = "id"
End Using
You can now get the id with this bit of code:
ComboBox1.SelectedValue.ToString()
And you can get the text with this bit of code:
ComboBox1.Text
Ok i use now that and works
Dim connetionString As String = Nothing
Dim connection As MySqlConnection
Dim command As MySqlCommand
Dim adapter As New MySqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
'connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword"
'sql = "select id,name from product"
sql = "SELECT id, CONCAT(name,' | ',id_maker,' | ',id_types) AS value FROM product ORDER BY name ASC"
'connection = New MySqlConnection(connetionString)
connection = New MySqlConnection(ConfigurationManager.ConnectionStrings("xCollectibles.My.MySettings.xcollectiblesConnectionString").ToString)
Try
connection.Open()
command = New MySqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "id"
ComboBox1.DisplayMember = "value"
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
Thanks you..

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

Value Parameter changes to 0

I want to display the data based on the value of the desired user, I tried to use a parameter that contains the value from the input. When I run the program data can not be performed. I'm trying to find my fault location code, by checking the value of limit_kar that holds the result of input from the user are the contents of the corresponding results of the input, when the limit_kar value stored into parameter changed to 0, I think a lot of errors in my code, please suggesting that the problem this can be resolved
I'm using VS 2008 and mysql
thank you
Newbie
this is mycode
Public Function Tampil_Stock(ByVal limit_kar As Integer) As List(Of Class_stock)
Dim tmpBaca As New List(Of Class_stock)
Dim cmd As New MySqlCommand
Dim dreader As MySqlDataReader
Dim ds As New DataSet
Dim sql As String
sql = "SELECT NoReg,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC Limit ?fn "
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.Int64)).Value = **limit_kar**
dreader = cmd.ExecuteReader
If dreader.HasRows Then
While dreader.Read
Dim objTemp As New Class_stock
objTemp.NoReg_ = dreader.Item("NoReg")
'objTemp.NoPin_ = dreader.Item("NoPin")
'objTemp.status_ = dreader.Item("status")
objTemp.status_kartu_ = dreader.Item("status_kartu")
tmpBaca.Add(objTemp)
End While
Else
MsgBox("Not Found")
End If
myconnection.close()
Return tmpBaca
'dreader.Close()
End Function
The syntax of your parameter declaration is incorrect. Look at the example here : http://www.devart.com/dotconnect/mysql/docs/Parameters.html.
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.Int64)).Value = limit_kar
This looks odd to me. Shouldn't Add take the value as parameter ? What is "?fn" ? Does Add really return the new MysqlParameter instance ?
The following sticks to the example from the docs. I still don't understand the reason why you are using ?fn and why you declare the type explicitly as MySqlDbType.Int64.
sql = "SELECT NoReg,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC Limit ?"
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add("limit_kar", limit_kar)