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).
Related
My code:
Private Sub btnEnviartranche_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnviartranche.Click
Try
connection.Close()
connection.Dispose()
connection.Open()
Dim busca As New MySqlCommand("SELECT MAX(cod_tranche) +1 As id_last_tranche FROM long_short_tranche", connection)
Dim adapter As New MySqlDataAdapter(busca)
Dim table As New DataTable()
adapter.Fill(table)
Dim retorno = busca.ExecuteReader
Dim id_ultima_tranche = ""
Dim tipo_operacao As String = dg_ctrlv.Rows(1).Cells(0).Value.ToString
Dim ativo As String = dg_ctrlv.Rows(2).Cells(2).Value.ToString
Dim quantidade As String = dg_ctrlv.Rows(2).Cells(3).Value.ToString
Dim preco_executado As String = dg_ctrlv.Rows(2).Cells(4).Value.ToString
If retorno.Read() Then
id_ultima_tranche = retorno.GetString(0)
End If
connection.Close()
connection.Dispose()
connection.Open()
Dim nova_tranche = id_ultima_tranche + 1
Dim hora = DateTime.Now
' ======= The error happens on the line below ========
Dim query As New MySqlCommand("INSERT INTO long_short_tranche (cod_tranche, cod_cliente, nocional, title_operation, tipo_operacao, ativo, quantidade, preco_executado, data_hora) SELECT ('" & nova_tranche & "', cod_cliente, nocional, title_operation,'" & hora & "','" & tipo_operacao & "','" & ativo & "','" & quantidade & "','" & preco_executado & "') FROM long_short WHERE title_operation = '" & cbox_operacao.Text & "' AND confirmacao = 'Sim' AND flg_visualizar = 1 ", connection)
Dim adapter2 As New MySqlDataAdapter(query)
Dim table2 As New DataTable()
adapter2.Fill(table2)
Dim retorno2 = query.ExecuteReader
MessageBox.Show("Dados atualizados com sucesso!")
Catch ex As Exception
MessageBox.Show("Erro ao consultar tabela!")
End Try
End Sub
This is what happens
This is crazy-vulnerable to sql injection. NEVER use string concatenation like that to put values into a query! It's very likely the problem is a stray apostrophe somewhere in the data, and proper SQL coding practice would have avoided this, while also fixing the MASSIVE security issue.
Try it like this:
Dim sql As String = "
INSERT INTO long_short_tranche
(cod_tranche, cod_cliente, nocional, title_operation, tipo_operacao, ativo, quantidade, preco_executado, data_hora)
SELECT #nova_tranche, cod_cliente, nocional, title_operation, #hora, #tipo_operacao, #ativo, #quantidade, #preco_executado
FROM long_short
WHERE title_operation = #operacao AND confirmacao = 'Sim' AND flg_visualizar = 1
"
Using connection As New MySqlConnection("connection string here")
Using query As New MySqlCommand(sql, connection)
query.Parameters.AddWithValue("#nova_tranche", nova_tranche)
query.Parameters.AddWithValue("#hora", hora)
query.Parameters.AddWithValue("#tipo_operacao", tipo_operacao)
query.Parameters.AddWithValue("#ativo", ativo)
query.Parameters.AddWithValue("#quantidade", quantidade)
query.Parameters.AddWithValue("#preco_executado", preco_executado)
query.Parameters.AddWithValue("#operacao", cbox_operacao.Text)
connection.Open()
query.ExecuteNonQuery() ' ...
End Using
End Using
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
I have a button "btnSetAppointment", I created a Scheduling system, and when I save an appointment it will automatically send a message to the patient's phone_number. However, I don't know how to get the value of phone_number from the table.
As you can see below, I declared number as string, I want to store the phone_number of a patient in the database.
Private Sub btnSetAppointment_Click(sender As Object, e As EventArgs) Handles btnSetAppointment.Click
'SMS
query = "SELECT * FROM schedule WHERE Phone_Number =" & frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value
cmd = New MySqlCommand(query, MySqlConn)
reader = cmd.ExecuteReader
Dim number1 As String
If reader.HasRows Then
number1 = frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value
With SerialPort1
.Write("at" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("at+cmgf=1" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("at+cmgs=" & Chr(34) & number1 & Chr(34) & vbCrLf)
.Write(sys_msg & Chr(26))
Threading.Thread.Sleep(1000)
MsgBox(rcvdata.ToString)
End With
End If
end sub
This is how I would do it using MySQL (after establishing a database connection).
Try
Dim MyDb As New Database_Connection
Dim query As String
query = "select phone_number from schedule where Phone_Number = '" & frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value & "'"
Dim myReader As OdbcDataReader = MyDb.ExecuteQuery(query)
myReader.Read()
If reader.HasRows Then
dim ph_number as string = myReader.Item(0)
.
.
.
End if
myReader.Close()
MyDb.Dispose()
Catch ex As System.Data.Odbc.OdbcException
'MessageBox.Show(ex.ToString)
End Try
I am making web page in asp.net & using mysql in backend.. My problem is onpage load data shows properly. I have applied some filter on data which is not working for me.
ERROR
System.InvalidOperationException: The CommandText property has not
been properly initialized. at
MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
at
VB Code
Protected Sub area_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles area.SelectedIndexChanged
Try
ViewState("Data") = ""
If area.SelectedValue <> "All" And board.SelectedValue <> "All" Then
query = "SELECT * FROM school"
ElseIf area.SelectedValue <> "All" And board.SelectedValue <> "All" Then
query = "SELECT * FROM `school` WHERE area = '" + area.SelectedValue + "';"
ElseIf area.SelectedValue <> "All" And board.SelectedValue <> "All" Then
query = "SELECT * FROM 'school' WHERE board = '" + board.SelectedValue + "'; "
End If
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(query, con)
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
cmd.CommandTimeout = 0
Using dt As New DataTable()
sda.Fill(dt)
ViewState("Data") = dt
schoollists.DataSource = dt
schoollists.DataBind()
End Using
End Using
End Using
End Using
countResult.Text = (" " & schoollists.Items.Count & " " & board.Text & " Schools Found in " & area.Text & " ")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Coonection String
<add name="constr" connectionString="Data Source=localhost;port=3306;Initial Catalog=vidyan;User Id=root;password="/>
i have problem to search and update record database sql.
this is my code. i using mysql database and Microsoft Visual Basic 2008
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t As New Threading.Thread(AddressOf closeMsgbox)
objconn = New MySqlConnection("server=localhost;database=AAA;userid=root;password= 'root'")
Dim username As Boolean = True
objconn.Open()
Dim sqlquery As String = "SELECT * FROM daftar WHERE nid = '" & FormRegister.TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = objconn
adapter.SelectCommand = command
data = command.ExecuteReader
If data.HasRows() = True Then
While data.Read()
FormRegister.Show()
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:ss")
command.Connection = objconn
command.CommandText = "UPDATE visitor SET tkhupd ='" & tkhupd & "' WHERE nokp = '" & FormRegister.TextBox1.Text & "';"
command.ExecuteNonQuery()
MessageBox.Show("You're has logout")
FormRegister.TextBox1.Text = ""
username = False
Me.Close()
End While
Else
FormRegister.Show()
username = True
End If
data.Close()
If username = True Then
Dim sqlquery2 As String = "INSERT INTO visitor (nid)VALUES ('" & FormRegister.TextBox1.Text & "')"
Dim data2 As MySqlDataReader
Dim adapter2 As New MySqlDataAdapter
Dim command2 As New MySqlCommand
command2.CommandText = sqlquery2
command2.Connection = objconn
adapter2.SelectCommand = command2
data2 = command2.ExecuteReader
MessageBox.Show("You're has login")
Form4.Show()
FormRegister.TextBox1.Text = ""
Me.Close()
End If
End Sub
but i have error on Word command.ExecuteNonQuery(): MySqlException was unhandled. There is already an open DataReader associated with this Connection which must be closed first
You need to use a separate MySqlCommand object, say command2 inside your While statement , because command is already in active use:
Dim command2 As New MySqlCommand
..
While data.Read()
..
command2.Connection = objconn
..
End While
I would do this all in one call to the database, comprising two statements. I'm more used to Sql Server, so this syntax may be a little off, but it would look something like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlquery As String = _
"DECLARE #RowCount Int;" & _
" UPDATE FROM visitor v" & _
" INNER JOIN daftar d ON d.nid = v.nokp" & _
" SET v.tkhupd = current_timestamp" & _
" WHERE d.nid = ?NID;" & _
" SELECT row_count() INTO #RowCount;" & _
" IF #RowCount = 0 THEN " & vbCrLf & _
" INSERT INTO visitor (nid) VALUES (?NID);" & vbCrLf & _
" END IF"
Using conn As New MySqlConnection("server=localhost;database=AAA;userid=root;password= 'root'"), _
cmd As New MySqlCommand(sqlquery, conn)
cmd.Parameters.Add("?NID", MySqlDbTypes.Int).Value = Integer.Parse(FormRegister.TextBox1.Text)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub