bar graph in vb.net using data from mysql database - mysql

I have created a private sub name graphloaddata and call it in MyBase.Load. What I want it to happen is I want the user to load data from specified date between from date to a certain date but what I get when I run my code it just simply added new graph details at the end. I want it to display only data from that specified date. How can I achieve this?
Imports MySql.Data.MySqlClient
Public Class graph
Dim dbconn As New MySqlConnection
Dim dbcomm As MySqlCommand
Dim dbread As MySqlDataReader
Private Sub graph_Load(sender As Object, e As EventArgs) Handles MyBase.Load
graphLoadData()
End Sub
Private Sub graphLoadData()
dbconn = New MySqlConnection("Data Source=localhost;user id=root; database=sample;")
Try
dbconn.Open()
Catch ex As Exception
MsgBox("Error in connection, please check Database and connection server.")
End Try
Dim sql As String
Try
Chart1.Series.Add("Department")
sql = "select count(u.idno), deptName from utilization u right join student s on u.idno = s.idno right join course c on c.course_id= s.course_id right join department d on c.deptID = d.deptID group by deptName " '= '" & month & "'
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
While dbread.Read
Chart1.Series("Department").Points.AddXY(dbread("deptName").ToString, dbread("Count(u.idno)").ToString)
End While
dbread.Close()
Catch ex As Exception
MsgBox("Error in saving to Database. Error is :" & ex.Message)
dbread.Close()
Exit Sub
Finally
dbread.Close()
dbconn.Dispose()
End Try
End Sub
Private Sub view_Click(sender As Object, e As EventArgs) Handles view.Click
dbconn = New MySqlConnection("Data Source=localhost;user id=root;database=sample;")
Try
dbconn.Open()
Catch ex As Exception
MsgBox("Error in connection, please check Database and connection server.")
End Try
Dim sql As String
'Dim month As String = graphDateTimePicker.Value.ToString("MMMM")
'MsgBox(month)
Try
Chart1.Series.Add("Specific")
sql = "select count(u.idno), deptName from utilization u join student s on u.idno = s.idno join course c on c.course_id= s.course_id join department d on c.deptID = d.deptID where date between '" + Format(fromdate.Value, "yyyy-MM-dd") + "' AND '" + Format(todate.Value, "yyyy-MM-dd") & "' group by deptName " '= '" & month & "'
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
While dbread.Read
Chart1.Series("Department").Points.AddXY(dbread("deptName").ToString, dbread("Count(u.idno)").ToString)
End While
dbread.Close()
Catch ex As Exception
MsgBox("Error in saving to Database. Error is :" & ex.Message)
dbread.Close()
Exit Sub
Finally
dbread.Close()
dbconn.Dispose()
End Try
End Sub
End Class
MyBase.Load image
After clicking view button something went wrong

Related

Get Result from mysql by vb.net

I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using

Increase value of data row of particular ID on button click

In my application customers book vehicle online & admin of site assigns duty to drivers which are already added. Below screen shot you can see the list of drivers.
Now what I am trying to do is if admin assigns some duty to some driver then in assign duty column should count which driver get how many duties. e.g. if admin assign duty to first driver then duty assign column should be updated by 1. Is it possible to do so? Below my code to assign duty to drivers
VB
Protected Sub assignDuty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles assignDuty.Click
Dim Did As String
Did = DriversList.SelectedItem.ToString
Try
Dim str1 As String = "UPDATE newBooking SET Assigned = '" & Did & "', status = 'Approved', DriverContact = '" + driverMobile.Text + "', vehicleNo = '" + vehicleNo.Text + "' WHERE Bid = '" & trackInput.Text + "'"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
data = command.ExecuteReader
con.Close()
send_customer_message()
send_driver_message()
customer_confirm_mail()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Protected Sub DriversList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DriversList.SelectedIndexChanged
Try
Dim str As String = "SELECT * FROM addDriver where DriverID='" + DriversList.SelectedValue.ToString + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
orderStatus.Visible = True
additionalDetail.Visible = True
vehicleNo.Text = dt.Rows(0)("VehicleRegistration").ToString
driverName.Text = dt.Rows(0)("DriverName").ToString
driverMobile.Text = dt.Rows(0)("contact")
'duration.Text = dt.Rows(0)("duration")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
UPDATE!
How admin assigns duty to drivers.
Admin receives mail when customer books online. He simply enters booking ID & click track orders & all details will be displayed in left side part. In right side he has list of drivers & he selects one & on select last section vehicle details get updated & finally he clicks on assign duty so databse get updated in newBooking table.
UPDATE!
Protected Sub assignDuty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles assignDuty.Click
Try
Dim Did As String
Did = DriversList.SelectedItem.ToString
Dim Query1 As String
Query1 = "UPDATE newBooking SET Assigned = '" & Did & "', status = 'Approved', DriverContact = '" + driverMobile.Text + "', vehicleNo = '" + vehicleNo.Text + "' WHERE Bid = '" & trackInput.Text + "'"
RunCommand(Query1)
Dim Query2 As String
Query2 = "UPDATE addDriver SET [DutyAssigned] = [DutyAssigned] + 1 WHERE DriverID = " & Did
RunCommand(Query2)
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Public Function RunCommand(ByVal myQry As String) As String
Try
Using _conn As New MySqlConnection("constr")
Using _comm As New MySqlCommand()
With _comm
.Connection = _conn
.CommandText = myQry
.CommandType = CommandType.Text
End With
_conn.Open()
_comm.ExecuteNonQuery()
End Using
End Using
RunCommand = ""
Catch ex As Exception
RunCommand = ex.Message
End Try
End Function
[![enter image description here][4]][4]
Check below code. Here you need to specify your connection string in RunCommand method. Let me know the results.
Protected Sub assignDuty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles assignDuty.Click
Try
Dim Did As String
Did = DriversList.SelectedItem.ToString
Dim DriverID As String
DriverID = DriversList.SelectedValue
Dim Query1 As String
Query1 = "UPDATE newBooking SET Assigned = '" & Did & "', status = 'Approved', DriverContact = '" + driverMobile.Text + "', vehicleNo = '" + vehicleNo.Text + "' WHERE Bid = '" & trackInput.Text + "'"
RunCommand(Query1)
Dim Query2 As String
Query2 = "UPDATE addDriver SET DutyAssigned = DutyAssigned + 1 WHERE DriverID = " & DriverID
RunCommand(Query2)
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Public Function RunCommand(ByVal myQry As String) As String
Try
Using _conn As New MySqlConnection("connectionStr here")
Using _comm As New MySqlCommand()
With _comm
.Connection = _conn
.CommandText = myQry
.CommandType = CommandType.Text
End With
_conn.Open()
_comm.ExecuteNonQuery()
End Using
End Using
RunCommand = ""
Catch ex As Exception
RunCommand = ex.Message
End Try
End Function
I would encourage you to use binding parameters instead of concatinating query string (like SELECT * FROM addDriver where DriverID=:DriverId and cmd.Parameter.Add("DriverId",MySqlType.Varchar,<fieldLength>,"DriverId". Do it also in the Update query.)
In assignDuty_Click you should use UpdateCommand instead of SelectCommand (I´m no MySql pro but SelectCommand smells for me).
For updating the Duty Assigned field enhance the Update string in assignDuty_Click with SET DutyAssigned = DutyAssigned + 1 ... (or whatever the field is named in newBooking).

How to populate a datagridview VB.Net

I have queried my MySql database and data is stored in a dataset named Search Events(I have checked this and it works)
However when i try to pass this data into a datagridview and then ultimately my array it doesn't seem to work :( The problem seems to be that no data is being passed from Search Events into Table
Any ideas??
Dim Table As New DataGridView
Table.DataSource = SearchEvents.Tables("Event ID")
Dim EventID(Table.Rows.Count - 1) As String
For i = 0 To 12
EventID(i) = Table.Rows(0).Cells(i).Value
Next
'Try the following function
Public Sub getuserlist()
Dim con As New MySqlConnection(ConnectionString)
Try
If con.State <> ConnectionState.Open Then
con.Open()
End If
Dim selecttaxinv = "SELECT * FROM user_tb WHERE user_status = 'Active' ORDER BY date_registered DESC"
Dim myCommand As New MySqlCommand(selecttaxinv, con)
Dim dr As MySqlDataReader
dr = myCommand.ExecuteReader()
yourdatagridview.Rows.Clear()
Dim b = 1
While dr.Read()
Dim fullname As String = dr("fname") & " " & dr("mname") & " " & dr("lname")
Dim row As String() = New String() {dr("user_id"), b, fullname, dr("fname"), dr("date_registered")}
yourdatagridview.Rows.Add(row) 'print list
b += 1
End While
dr.Close()
If con.State = ConnectionState.Open Then
con.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub

VB-SQL, Exception in SELECT statement

Imports System.Data.SqlClient
Public Class Form3
Private cs As New SqlConnection("Data Source=HUSAIN-PC;Initial
Catalog=final1;Integrated Security=True")
Private da As New SqlDataAdapter
Private ds As New DataSet
Public dr As SqlDataReader
Public cmd As New SqlCommand
Private sql As String
Private sqlsel As String
Dim Bal As String
Dim id As String
Dim amt As String
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cs.Open()
cmd.Connection = cs
amt = TextBox2.Text
id = TextBox1.Text
sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sqlsel, cs)
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While (dr.Read())
Bal = dr("Id")
End While
End If
dr.Close()
MessageBox.Show("Balance is :" + Bal)
Dim total As String = Bal + amt
sql = "UPDATE db5 SET Bal='" + total + "' WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sql, cs)
da.InsertCommand.ExecuteNonQuery()
MessageBox.Show("updated")
End Sub
End Class
This is my VB code to retrieve a value from the SQL DB...the Update statement is running fine bt wen i write the select i get an exception in the code:
dr=cmd.ExecuteReader
"ExecuteReader: CommandText property has not been initialized"
Look at this code:
sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sqlsel, cs)
dr = cmd.ExecuteReader
You're specifying an InsertCommand as a SELECT query, but then you're calling ExecuteReader on a completely separate SqlDataReader... which hasn't got a query configured, as per the error message.
That's why you're getting this specific error, but there are lots of problems with this code:
You should be creating a new SqlConnection / SqlCommand etc every time you want to execute a query
You should be using Using statements to automatically close them
You shouldn't have instance variables for these - they should be local variables
I see no reason to use a DataAdapter here in the first place - just use SqlCommand.ExecuteNonQuery
Very important: You should be using parameterized SQL instead of including values directly in your SQL. See the Bobby Tables site for more information about this topic.

Inserting data into a MySQL table using VB.NET

I have a problem inserting data into a table on a MySQL database using a VB.NET application.
I have a simple form where when I set some data to the textboxes and I press a GO button, the code should execute a function called InsertCar() that takes all these values and insert them into the database and then return true if the transaction is done successfully or false otherwise. My problem is that nothing is being inserted into the table.
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Imports System
Imports System.Data
Public Class Form1
Dim connectionString As String = "Server=localhost; User Id=root; Password=123456; Database=uni_park_db"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim oDt_sched As New DataTable()
//SOME CODE For other buttons//
//Code for a button where the InsertCar() function is called at the beginning//
Public Function InsertCar() As Boolean
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
Dim sqlCommand As New MySqlCommand
Dim str_carSql As String
Try
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values ('" + TextBox20.Text + "','" + TextBox20.Text + "','" + TextBox23.Text + "','" + TextBox24.Text + "','" + TextBox22.Text + "','" + TextBox21.Text + "','" + ComboBox1.SelectedItem + "')"
MsgBox(str_carSql)
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
MsgBox("Error occured: Could not insert record")
End Try
End Function
End Class
I am using this MsgBox(str_carSql) to test if the SQL statement is correct and it is correct.
Any help will be appreciated.
UPDATE
I did the following and it stills not working
Public Function InsertCar() As Boolean
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Dim sqlCommand As New MySqlCommand
Dim str_carSql As String
Try
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (#id,#m_id,#model,#color,#ch_id,#pt_num,#code)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("#id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("#m_id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("#model", TextBox23.Text)
sqlCommand.Parameters.AddWithValue("#color", TextBox24.Text)
sqlCommand.Parameters.AddWithValue("#ch_id", TextBox22.Text)
sqlCommand.Parameters.AddWithValue("#pt_num", TextBox21.Text)
sqlCommand.Parameters.AddWithValue("#code", ComboBox1.SelectedItem)
sqlCommand.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
MsgBox("Error occured: Could not insert record")
End Try
End Function
UPDATE
The Insert is not working either, I will post the entire code maybe a problem is found elsewhere
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Imports System
Imports System.Data
Public Class Form1
Dim connectionString As String = "Server=localhost; User Id=root; Password=123456; Database=uni_park_db"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim oDt_sched As New DataTable()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If SQLConnection.State = ConnectionState.Open Then
If TextBox1.Text = "" Then
MsgBox("Please Input a Valid ID")
Else
Dim myAdapter1 As New MySqlDataAdapter("select m.work_date as Work, m.time_in as Start, m.time_out as End from university_members as u inner join members_schedule as m on u.members_schedule_id=m.members_schedule_id where member_id = " & TextBox1.Text, SQLConnection)
Dim myAdapter As New MySqlDataAdapter("select member_id, first_name, last_name, type from university_members, members_schedule where(university_members.members_schedule_id = members_schedule.members_schedule_id) AND member_id = " & TextBox1.Text, SQLConnection)
Dim mydatatable As New DataTable()
Dim dataset As New DataSet()
myAdapter.Fill(mydatatable)
If (mydatatable.Rows.Count > 0 And myAdapter1.Fill(dataset)) Then
TextBox2.Text = mydatatable.Rows(0).Item("first_name")
TextBox3.Text = mydatatable.Rows(0).Item("last_name")
TextBox4.Text = mydatatable.Rows(0).Item("type")
TextBox20.Text = mydatatable.Rows(0).Item("member_id")
DataGridView1.DataSource = dataset.Tables(0)
oDt_sched = dataset.Tables(0)
Else
MsgBox("Check Error: ID Not Found! Enter a Valid ID")
TextBox1.Text = "Example 123456 "
TextBox2.Text = " "
TextBox3.Text = " "
TextBox4.Text = " "
End If
End If
Else
MsgBox("Database Connection Error: Database Connection Not Established. Please Connect First.")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub DatabaseConnectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DatabaseConnectToolStripMenuItem.Click
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Database Connection Sccessfully Established")
Else
SQLConnection.Close()
MsgBox("Database Connection Terminated")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
TextBox1.Text = "Example 123456 "
TextBox2.Text = " "
TextBox3.Text = " "
TextBox4.Text = " "
DataGridView1.Columns.Clear()
DataGridView1.DataSource = Nothing
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str_sql As String = ""
Dim obj_msadapter As MySqlDataAdapter
Dim i_maxh As Integer
Dim i_beginh As Integer
Dim ods_avail As DataSet = New DataSet()
Dim str_err As String = ""
Dim i_strth As Integer
Dim odt_avail As New DataTable()
Dim odrcol_avail() As DataRow
Dim str_range As String = ""
Try
'perform insert car here (boolean to see if the code continues running)
''''''''''''''''''''''''''
If InsertCar() Then
For Each odr As DataRow In oDt_sched.Rows
i_maxh = odr(2)
i_beginh = odr(1)
i_strth = odr(1) + 2
str_range = ""
str_sql = "select * from parked_cars where pwork_date='" & odr(0).ToString() & "'"
ods_avail = New DataSet()
obj_msadapter = New MySqlDataAdapter(str_sql, SQLConnection)
obj_msadapter.Fill(ods_avail)
odt_avail = ods_avail.Tables(0)
If odt_avail.Rows.Count < 210 Then
While (i_strth <= i_maxh)
odrcol_avail = odt_avail.Select("ptime_in='" + i_beginh.ToString() + "' and ptime_out='" + i_strth.ToString() + "'")
If odrcol_avail.Count < 30 Then
str_range += i_beginh.ToString() + ";" + i_strth.ToString()
Else
str_range += "0"
End If
i_strth += 2
i_beginh += 2
End While
FillSpots(str_range, odr(0).ToString())
Else
str_err += "no place on day: " + odr(0).ToString() + ";"
MsgBox("No place is found on this day")
End If
Next
End If
Catch ex As Exception
MsgBox("")
End Try
End Sub
Public Function FillSpots(ByVal blowf As String, ByVal _day As String) As Boolean
Dim str_unit As String
Dim i_count As Integer = 0
Dim str_i_strt As String
Dim str_i_end As String
Dim str_sql As String
Try
For Each str_unit In blowf.Split("0")
If str_unit <> "" Then
str_i_strt = str_unit.Split(";")(0)
str_i_end = str_unit.Split(";")(str_unit.Split(";").Length - 1)
str_sql = "insert into parked_cars values ('" + TextBox20.Text + "','" + _day + "','" + str_i_strt + "','" + str_i_end + "')"
End If
Next
Return True
Catch ex As Exception
Throw ex
End Try
End Function
Public Function InsertCar() As Boolean
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Dim sqlCommand As New MySqlCommand
Dim str_carSql As String
Try
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.CommandType = CommandType.Text
sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
sqlCommand.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
MsgBox("Error occured: Could not insert record")
End Try
End Function
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
ComboBox1.ResetText()
TextBox21.Text = " "
TextBox22.Text = " "
TextBox23.Text = " "
TextBox24.Text = " "
DataGridView2.Columns.Clear()
DataGridView2.DataSource = Nothing
End Sub
End Class
Thanks everyone for the help. This is the solution that worked for me
Dim iReturn as boolean
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO members_car (`car_id`, `member_id`, `model`, `color`, `chassis_id`, `plate_number`, `code`) values (#xid,#m_id,#imodel,#icolor,#ch_id,#pt_num,#icode)"
.Connection = SQLConnection
.CommandType = CommandType.Text // You missed this line
.Parameters.AddWithValue("#xid", TextBox20.Text)
.Parameters.AddWithValue("#m_id", TextBox20.Text)
.Parameters.AddWithValue("#imodel", TextBox23.Text)
.Parameters.AddWithValue("#icolor", TextBox24.Text)
.Parameters.AddWithValue("#ch_id", TextBox22.Text)
.Parameters.AddWithValue("#pt_num", TextBox21.Text)
.Parameters.AddWithValue("#icode", ComboBox1.SelectedItem)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = TRUE
Catch ex As MySqlException
MsgBox ex.Message.ToString
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return iReturn
After instantiating the connection, open it.
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Also, avoid building SQL statements by just appending strings. It's better if you use parameters, that way you win on performance, your program is not prone to SQL injection attacks and your program is more stable. For example:
str_carSql = "insert into members_car
(car_id, member_id, model, color, chassis_id, plate_number, code)
values
(#id,#m_id,#model,#color,#ch_id,#pt_num,#code)"
And then you do this:
sqlCommand.Parameters.AddWithValue("#id",TextBox20.Text)
sqlCommand.Parameters.AddWithValue("#m_id",TextBox23.Text)
' And so on...
Then you call:
sqlCommand.ExecuteNonQuery()
You need to open the connection first:
SQLConnection.Open();
Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean
Private Sub Insert_Car()
Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (#car_id,#member_id,#model,#color,#chassis_id,#plate_number,#code)"
Dim cmd = new MySqlCommand(sql, conn)
cmd.Paramaters.AddwithValue("#car_id", txtCar.Text)
cmd.Paramaters.AddwithValue("#member_id", txtMember.Text)
cmd.Paramaters.AddwithValue("#model", txtModel.Text)
cmd.Paramaters.AddwithValue("#color", txtColor.Text)
cmd.Paramaters.AddwithValue("#chassis_id", txtChassis.Text)
cmd.Paramaters.AddwithValue("#plate_number", txtPlateNo.Text)
cmd.Paramaters.AddwithValue("#code", txtCode.Text)
Try
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then
ireturn = True
End If
conn.Close()
Catch ex as Exception
ireturn = False
conn.Close()
End Try
Return ireturn
End Sub
your str_carSql should be exactly like this:
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (#id,#m_id,#model,#color,#ch_id,#pt_num,#code)"
Good Luck
You need to use ?param instead of #param when performing queries to MySQL
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
sqlCommand.ExecuteNonQuery()
Change the catch block to see the actual exception:
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
First, You missed this one: sqlCommand.CommandType = CommandType.Text
Second, Your MySQL Parameter Declaration is wrong. It should be # and not ?
try this:
Public Function InsertCar() As Boolean
Dim iReturn as boolean
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO members_car (`car_id`, `member_id`, `model`, `color`, `chassis_id`, `plate_number`, `code`) values (#xid,#m_id,#imodel,#icolor,#ch_id,#pt_num,#icode)"
.Connection = SQLConnection
.CommandType = CommandType.Text // You missed this line
.Parameters.AddWithValue("#xid", TextBox20.Text)
.Parameters.AddWithValue("#m_id", TextBox20.Text)
.Parameters.AddWithValue("#imodel", TextBox23.Text)
.Parameters.AddWithValue("#icolor", TextBox24.Text)
.Parameters.AddWithValue("#ch_id", TextBox22.Text)
.Parameters.AddWithValue("#pt_num", TextBox21.Text)
.Parameters.AddWithValue("#icode", ComboBox1.SelectedItem)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = TRUE
Catch ex As MySqlException
MsgBox ex.Message.ToString
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return iReturn
End Function