How to get the value of a column and cell data? - mysql

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

Related

Bulk update mysql table and calculate value from datagridview. VB.NET

I want to do bulk update my database table using value from datagridview, but also I need to sum the datagridview and mysql table value fisrt.
how do I do that?
here is my current code of my update button
attached image
For Each row As DataGridViewRow In dgvStok.Rows
If (Not row.IsNewRow) Then
Dim ID As DataGridViewCell = row.Cells("ID").Value
Dim Stok As DataGridViewCell = row.Cells("Stok").Value
conn = New MySqlConnection('myconnstring)
conn.Open()
cmd = New MySqlCommand("Select * from tbStok where ID='" & ID & "'", conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
Dim StokInventory, IncomingStok As Integer
StokInventory = dr.Item("Stok")
TotalStok = StokInventory + IncomingStok
Dim updateStok As String = "update tbStok set Stok ='" & TotalStok & "' where ID = '" & ID & "'"
cmd = New MySqlCommand(updateStok, conn)
cmd.ExecuteNonQuery()
End If
conn.Close()
End If
Next
I've found my solution
Private Sub UpdateBTN_Click(sender As Object, e As EventArgs) Handles UpdateBTN.Click
Dim ID As String
Dim StartingStok, IncomingStok, TotalStok As Integer
For Each DGVR As DataGridViewRow In dgvStok.Rows
ID = (DGVR.Cells("ID").Value)
IncomingStok= (DGVR.Cells("Stok").Value)
#open mysql connection string
cmd = New MySqlCommand("Select * from tbStok where ID='" & ID & "'", conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
StartingStok = dr.Item("Stok")
End If
conn.Close()
TotalStok = StartingStok + IncomingStok
#open mysql connection string
Dim UpdateTable As String = "update tbStok set Stok ='" & TotalStok & "' where ID = '" & ID & "'"
cmd = New MySqlCommand(UpdateTable, conn)
cmd.ExecuteNonQuery()
conn.Close()
Next
End Sub
This code will looping through datagridview and sum value from datagridview and mysql table for each ID(primary key) and then it will update the table with new value which is from summarizing datagridview table and mysql table for each ID

Built in table with users email and password only allows every other user to log in

I have a vb.net app with a mysql database and a table for users emails and passwords. I started noticing that some could log in and others could not, so I tried all user accounts myself and found that all of the odd number indexed logins work and all of the even number indexed logins do not. I don't have a clue as to why this is not working.
Code below:
Partial Public Class Login
Inherits Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Email.Focus()
End Sub
Protected Sub LogIn(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim conn As New MySqlConnection
Dim cmd As MySqlCommand
Dim rdr As MySql.Data.MySqlClient.MySqlDataReader
Dim query As String
Dim name As String = ""
Dim time_out As Integer
Dim user_access As Integer
Dim pswrd As String
Dim e_mail As String
Dim firstname As String
Dim lastname As String
Try
conn = New MySqlConnection(connStr)
conn.Open()
query = "SELECT * FROM user"
cmd = New MySqlCommand(query, conn)
rdr = cmd.ExecuteReader
Do While rdr.HasRows = True
firstname = ""
lastname = ""
pswrd = ""
time_out = 0
user_access = 1
rdr.Read()
firstname = rdr.GetString(rdr.GetOrdinal("first_name"))
lastname = rdr.GetString(rdr.GetOrdinal("last_name"))
e_mail = rdr.GetString(rdr.GetOrdinal("email"))
pswrd = rdr.GetString(rdr.GetOrdinal("password"))
user_access = rdr.GetString(rdr.GetOrdinal("access"))
time_out = rdr.GetString(rdr.GetOrdinal("timeout"))
If pswrd = Password.Text And e_mail = Email.Text Then
session_email = e_mail
session_access = user_access
session_timeout = time_out
session_first = firstname
Session("Session_User") = session_email
Session("Session_TimeOut") = time_out
Session("Session_Access") = session_access
Session("Session_First") = session_first
Response.Write(session_first & " your access level is ... " & session_access & vbCrLf & "With an access level of... " _
& vbCrLf & "1 You can create work orders And view most other things" _
& vbCrLf & "2 You can create work orders, View and or Modify some items. Please be careful" _
& vbCrLf & "3 You have full Create, Edit and Delete access. Please be careful Jedi Master!" _
& vbCrLf & vbCrLf & "You have " & time_out & " minutes to complete your task.", vbSystemModal, "Logged In")
GoTo JumpPoint2
End If
If rdr.Read() = False Then
Response.Write("Your Login Attempt Failed " & vbCrLf & "Either your email address or password are NOT correct" & vbCrLf & "or you do not have access to this system yet." & vbCrLf & "Contact Management if you need an account set up for you.", vbSystemModal, "Log In Failure")
GoTo JumpPoint1
End If
Loop
JumpPoint1:
Catch ex As Exception
Response.Write("Login Fail by Exception : " & vbCrLf & vbCrLf & ex.Message)
End Try
JumpPoint2:
conn.Close()
If session_access = "1" Or session_access = "2" Or session_access = "3" Then
Response.Redirect("~/MainMenu.aspx")
End If
End Sub
End Class
End of Code:
Any ideas would be appreciated.
That is because you are calling .Read twice for each iteration in your loop, which will skip every other row. Change your loop to this:
Dim bolValidated As Boolean = False
Do While rdr.Read()
..
'Update bolValidated to True if you find a match.'
Loop
If Not bolValidated Then
Response.Write("Your Login Attempt Failed ...")
End If
The better solution though would to change your SQL statement to reduce processing:
SELECT TOP(1) * FROM User WHERE email = #Email AND password = #Password
Wrapping the connection in a using statement wouldn't be a bad idea either.

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

Update all data in columns in Datagrid except ID (MySQL Database VB.NET)

here's the function of my program. It is a Patient management system, the system has the ability to add, delete, and update but I coded an Auto generate Random key which will create random keys, i unchecked primary key on ID column on Mysql database, datatype is INT, so this program will generate a random IDs automatically when adding a record instead of MySql database auto generate ID (numeric in order). The Problem is When I click the update button, it tells that my syntax isn't correct and sometimes it shows "Duplicate entry key 'xxxxx' for key PRIMARY " which means that it DUPLICATES or REPLACE or Saving again the ID. my Question is
HOW TO UPDATE ALL RECORDS IN COLUMNS WITHOUT CHANGING or AFFECTING THE ID keys?
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
MySqlConn = New MySqlConnection
MySqlConn = New MySqlConnection("server=localhost;user id=root;password=root;database=PatientManagementSystem;")
MySqlConn.Open()
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("UPDATE newpatient SET " &
"ID='{0}', " &
"Lastname='{1}', " &
"Firstname= '{2}', " &
"Middlename= '{3}', " &
"Age= '{4}', " &
"Gender= '{5}', " &
"Address= '{6}', " &
"Occupation= '{7}', " &
"Month= '{8}', " &
"Day= '{9}', " &
"Year= '{10}'",
txtID.Text,
txtFirstname.Text,
txtFirstname.Text,
txtMiddlename.Text,
txtAge.Text,
cmbGender.SelectedItem,
txtAddress.Text,
txtOccupation.Text,
cmbMonth.SelectedItem,
cmbDay.SelectedItem,
cmbYear.SelectedItem)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Record successfully updated!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Updating record failed.", MsgBoxStyle.Critical, "Failed")
End If
MySqlConn.Close()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
MySqlConn = New MySqlConnection
MySqlConn = New MySqlConnection("server=localhost;user id=root;password=root;database=PatientManagementSystem;")
MySqlConn.Open()
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES ('{0}' , '{1}' ,'{2}' ,'{3}' ,'{4}' ,'{5}' , '{6}', '{7}', '{8}', '{9}', '{10}' )",
txtID.Text,
txtLastname.Text,
txtFirstname.Text,
txtMiddlename.Text,
txtAge.Text,
cmbGender.SelectedItem,
txtAddress.Text,
txtOccupation.Text,
cmbMonth.SelectedItem,
cmbDay.SelectedItem,
cmbYear.SelectedItem)
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Dim adapter As New MySqlDataAdapter
Dim DataSet As New DataTable
Dim binding As New BindingSource
'REFRESH DATAGRID
Try
frmOld_Patient.Show()
Dim query As String
Dim cmd1 As MySqlCommand
query = "SELECT * FROM PatientManagementSystem.newpatient"
cmd1 = New MySqlCommand(query, MySqlConn)
adapter.SelectCommand = cmd1
adapter.Fill(DataSet)
binding.DataSource = DataSet
frmOld_Patient.dgvRecords.DataSource = binding
adapter.Update(DataSet)
MySqlConn.Close()
frmOld_Patient.Select()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
End If
MySqlConn.Close()
End Sub
Your Update statement dose not have Where Condition so it will update all rows in your table with the same ID that why you get that error
EDIT : Just add WHERE TO your update statement like this
cmd.CommandText = String.Format("UPDATE newpatient SET " &
"ID='{0}', " &
"Lastname='{1}', " &
"Firstname= '{2}', " &
"Middlename= '{3}', " &
"Age= '{4}', " &
"Gender= '{5}', " &
"Address= '{6}', " &
"Occupation= '{7}', " &
"Month= '{8}', " &
"Day= '{9}', " &
"Year= '{10}'" &
"WHERE ID={11}, ' here we add where
txtID.Text,
txtFirstname.Text,
txtFirstname.Text,
txtMiddlename.Text,
txtAge.Text,
cmbGender.SelectedItem,
txtAddress.Text,
txtOccupation.Text,
cmbMonth.SelectedItem,
cmbDay.SelectedItem,
cmbYear.SelectedItem,
yourID)

how to search and update record mysql in vb

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