VB-SQL, Exception in SELECT statement - mysql

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.

Related

Save Datagridview if it is Checked by CheckboxColumn

Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next

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

bar graph in vb.net using data from mysql database

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

ComboBox and showing from datagrid

Can someone help me out. I have a combobox where the items are from my database. If I drop down the combobox and select an item, the datagridview must show the firstname,lastname etc. My data type at studentno is varchar, the int does not work too. The data will be get from two different table
2nd is how can I refresh the combobox? Because I need to close then reopen the program before the data that will be insert at combobox.
Private Sub ComboBox6_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox6.SelectedIndexChanged
conn.Open()
query = "select student.studentno,student.firstname,student.middlename,student.lastname,subject.subjcode,subject.subjdesc from student,subject where student.studentno = '" & ComboBox6.SelectedText & "' "
cmd = New MySqlCommand(query, conn)
da.SelectCommand = cmd
ds = New DataSet
da.Fill(ds, "ds_student,subject")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "ds_student,subject"
conn.Close()
End Sub
I had the same problem as you and then i came up with this
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Folha de Obra com Tabela Clientes.accdb;Persist Security Info=True")
Dim query As String
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
conn.Open()
query = ("select * from Obras where IdCliente = " & ComboBox1.ValueMember)
cmd = New OleDb.OleDbCommand(query, conn)
da.SelectCommand = cmd
da.Fill(ds, "NomeObra")
ComboBox2.DataSource = ds.Tables(0)
ComboBox2.DisplayMember = "NomeObra"
ComboBox2.ValueMember = "IdCliente"
conn.Close()
End Sub
I hope it helps you

Importing contents of text file into MySQL using VB.Net

Good day everyone. I am trying to create a program that will transfer all of the contents of a text file into a database. So far, my code works, but my code only inserts the first line of the text file into the database. What should I add to solve the problem? I am noob at programming sorry.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim Query As String
Dim data As String = System.IO.File.ReadAllText(filename)
Dim Loc, _date, time, temp, id As String
Loc = data.Substring(0, 3)
_date = data.Substring(3, 8)
time = data.Substring(11, 4)
temp = data.Substring(15, 3)
id = data.Substring(18, 3)
Query = "INSERT INTO tbl_entrance_swipe VALUES ('" + Loc + "','" + _date + "','" + time + "','" + temp + "','" + id + "')"
Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
Try
con.Open()
Dim sql As MySqlCommand = New MySqlCommand(Query, con)
sql.ExecuteNonQuery()
MsgBox("Record is Successfully Inserted")
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Record is not Inserted" + ex.Message)
End Try
End Sub
End Class
You are using File.ReadAllText which reads the complete text of the file. You want to read line by line, therefore you can use File.ReadLines(deferred executed) or File.ReadAllLines(reads all into a String()).
You should also use sql-parameters to prevent sql-injection and incorrect implicit type conversions or localization issues. Finally, use the Using statement to ensure that all unmanaged resources are disposed (f.e. the connection gets closed even on error):
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim allLines As String() = File.ReadAllLines(filename)
Dim query As String = "INSERT INTO tbl_entrance_swipe VALUES (#Loc, #Date, #Time, #Temp, #Id)"
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim loc, dt, time, temp, id As String
loc = line.Substring(0, 3)
dt = line.Substring(3, 8)
time = line.Substring(11, 4)
temp = line.Substring(15, 3)
id = line.Substring(18, 3)
cmd.Parameters.Clear()
Dim pLoc As New MySql.Data.MySqlClient.MySqlParameter("#Loc", MySqlDbType.VarChar)
pLoc.Value = loc
cmd.Parameters.Add(pLoc)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.VarChar)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
Dim pTemp As New MySql.Data.MySqlClient.MySqlParameter("#Temp", MySqlDbType.VarChar)
pTemp.Value = temp
cmd.Parameters.Add(pTemp)
Dim pId As New MySql.Data.MySqlClient.MySqlParameter("#Id", MySqlDbType.VarChar)
pId.Value = id
cmd.Parameters.Add(pId)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using