I want to update my table with replace function, but the result is not my expected result, how can I solve this problem?
Lets say I have a LONGTEXT columns(using_id) with value like this 1,2,3,4,5,6,7,8,9,10,11,
Now I want to remove '1,' so I write in this way:-
Dim query As String = "UPDATE curr_id SET using_id = REPLACE(using_id,'" & $"{g_currTicketID}," & "','')"
But the result become 2,3,4,5,6,7,8,9,10,1 How can I keep my '11,'?
Expected result: 2,3,4,5,6,7,8,9,10,11,
Public Sub TicketStatusUpdate(p_str As String)
'Login => GET NEXT ID > UPDATE USING ID > UPDATE NEXT ID
'Sales => RELEASE > UPDATE USED ID > GET NEXT ID > UPDATE USING ID > UPDATE NEXT ID
Select Case p_str
Case "UPDATE USED ID"
TicketStatusUpdate("RELEASE")
Dim query As String = "UPDATE curr_id SET used_id = CONCAT(used_id, '" & $"{g_currTicketID}," & "')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
TicketStatusUpdate("GET NEXT ID")
Case "GET NEXT ID"
Dim query_select = "SELECT * FROM curr_id WHERE DATE(curr_date) = '" & Format(DateTime.Today.Date, "yyyy-MM-dd") & "' "
Dim reader As MySqlDataReader
Dim IsNewDay As Boolean = False
Using cmd = New MySqlCommand(query_select, conn)
reader = cmd.ExecuteReader
reader.Read()
If reader.HasRows Then
g_currTicketID = reader.GetInt32("next_id")
Else
g_currTicketID = 1
IsNewDay = True
End If
reader.Close()
End Using
If IsNewDay Then TicketStatusUpdate("RESET")
TicketStatusUpdate("UPDATE USING ID")
TicketStatusUpdate("UPDATE NEXT ID")
Case "UPDATE USING ID"
Dim query As String = "UPDATE curr_id SET using_id = CONCAT(using_id, '" & $"{g_currTicketID}," & "')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
Case "UPDATE NEXT ID"
Dim query1 As String = "SELECT * FROM curr_id"
Dim str_usingID As String = ""
Dim str_usedID As String = ""
Dim reader As MySqlDataReader
Using cmd = New MySqlCommand(query1, conn)
reader = cmd.ExecuteReader
reader.Read()
str_usingID = reader.GetString("using_id").ToString
str_usedID = reader.GetString("used_id").ToString
reader.Close()
End Using
Dim str_allID As String = (str_usingID + str_usedID).TrimEnd(",")
Dim strArray As String() = str_allID.Split(",")
Dim intArray As Integer() = Array.ConvertAll(strArray, Function(s) Int32.Parse(s))
Array.Sort(Of Integer)(intArray)
Dim nextID As Integer = FirstMissing(intArray)
Dim query2 As String = "UPDATE curr_id SET next_id = '" & nextID & "'"
Using cmd = New MySqlCommand(query2, conn)
cmd.ExecuteNonQuery()
End Using
Case "RELEASE"
Dim query As String = "UPDATE curr_id SET using_id = REPLACE(using_id,'" & $"{g_currTicketID}," & "','')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
Case "RESET"
Dim query As String = "UPDATE curr_id SET next_id='',used_id='',using_id=''"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Select
End Sub
Private Function FirstMissing(sequence() As Integer) As Integer
Dim seq = sequence
Dim firstMissingNumer = Int32.MinValue
For i = 1 To Math.Min(seq.Last, seq.Count)
If seq(i - 1) <> i Then
firstMissingNumer = i
Exit For
End If
Next
If firstMissingNumer = Int32.MinValue Then
Return seq.Max + 1
Else
Return firstMissingNumer
End If
End Function
When I logout the application it will call TicketStatusUpdate("RELEASE") to remove the g_currTicketID from using_id column.
Examples:
g_currTicketID = 1
using_id = 1,11,21,31,
When TicketStatusUpdate("RELEASE") called it will remove all '1,' from using_id, so the result will become 1,2,3 which is not the result that I want, I only want to remove '1,' and keep '11,21,31,'
Instead of replace just value, you could try to replace both value and boundary character
(in your case, comma ',' is a boundary character).
Example:
With g_currTicketID = 1, using_id = 1,11,21,31, then
replaceValue = CONCAT(',',g_currTicketID,',') = ',1,'
stringToReplace = CONCAT(',',using_id,',') = ',1,11,21,31,'
using_id = TRIM(BOTH ',' FROM REPLACE(stringToReplace, replaceValue, ','))
Your updat statement could be like this
Dim query As String = "UPDATE curr_id SET using_id = TRIM(BOTH ',' FROM REPLACE(CONCAT(',' ,using_id, ','), '," & $"{g_currTicketID}," & "', ','))"
I was making a vb program that searches a student info by searching a course.. For example Ajax's course is "BSCS" and DP's course is "BSIT" , then i'm going to select BSCS, so Ajax's must only appear not DP. The result appear's in DataGridView
myConnection.Open()
Dim str As String
str = "SELECT * FROM students WHERE (Course = '" & TextBox1.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
FirstNameTextBox = dr("FirstName")
MiddleNameTextBox = dr("MiddleName")
LastNameTextBox = dr("LastName")
AddressTextBox = dr("Address")
CellphoneNumberTextBox = dr("CellphoneNumber")
CourseTextBox = dr("Course")
End While
myConnection.Close()
Based on your Code you should add new DataGridView to your form and also adding columns with header name that you choose and replace the code with mine
myConnection.Open()
Dim str As String
str = "SELECT * FROM students WHERE (Course = '" & TextBox1.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
DataGridView1.Rows.Add({dr("FirstName"), dr("MiddleName"), dr("LastName"), dr("Address"), dr("CellphoneNumber"), dr("Course")})
End While
myConnection.Close()
For i As Integer = Me.DataGridView1.SelectedRows.Count - 1 To 0 Step -1
Dim SDA1 As New MySqlDataAdapter
Dim bSource1 As New BindingSource
Dim dbDataSet1 As New DataTable
qty = DataGridView1.Rows(i).Cells(0).Value
auth = DataGridView1.Rows(i).Cells(1).Value()
title = DataGridView1.Rows(i).Cells(2).Value()
callnumber = DataGridView1.Rows(i).Cells(3).Value()
shelf = DataGridView1.Rows(i).Cells(4).Value()
Dim Query As String
Query = "Insert into returnedlist(quantity,author,title ,call_number,shelf,student_id,due_date,date_added) values('" & qty & "','" & auth & "','" & title & "','" & callnumber & "','" & shelf & "','" & TextBox2.Text.ToString & "','" & DateTimePicker1.Text & "', Now())"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA1.SelectCommand = COMMAND
SDA1.Fill(dbDataSet1)
bSource1.DataSource = dbDataSet1
Me.DataGridView1.DataSource = bSource1
SDA1.Update(dbDataSet1)
Next
**Code for Select**
ElseIf ComboBox2.Text = "Author" Then
Dim Query As String
Query = "Select id as 'ID', quantity as 'Qty',author as 'Author',title as 'Title',call_number as 'Call Number',location as 'Shelf #' from librarydb.blist where author like'%" & TextBox1.Text & "%' ORDER by author"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
If SDA.Fill(dbDataSet) Then
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
TextBox1.Text = ""
ComboBox2.Text = ""
Else
TextBox1.Text = ""
ComboBox2.Text = ""
MessageBox.Show("No Results found", "Informed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
what i want to do is i want to insert in the db what i have selected row in the Datagridview.
The code works but the problem is :
even if i choose to select the row3, it always fall inserting to db the row1 in the datagridview.
Does it have to do on the properties of my Datagridview?
The Update method of the MySqlDataAdapter has the capability to update all the rows present in the DataTable passed as input that have the RowState property different from the value Unchanged.
When you edit a DataGridView binded to a DataTable the changes made on the grid are immediately reflected in the underlying DataTable and the row edited will have its RowState property changed accordingly to the edit made.
To make this work you need a couple of things.
First declare globally the MySqlDataAdapter used to retrieve the datatable
Dim SDA1 As MySqlDataAdapter
then in the code that loads the datatable be sure to include also the column that is your primary key
' Here ID is assumed to be your primarykey'
SDA1 = New MySqlDataAdapter("SELECT ID, ...... FROM returnedlist", connection)
SDA1.Fill(yourDataTable)
Dim bSource1 As New BindingSource
bSource1.DataSource = yourDataTable
dataGridView1.DataSource = bSource1
Now you use an MySqlCommandBuilder to automatically create the InsertCommand, UpdateCommand and DeleteCommand properties of your MySqlDataAdapter
Dim builder = new MySqlCommandBuilder(SDA1)
Finally, when you are ready to update your data, you write simply
Dim yourBindingSource = dataGridView1.DataSource As BindingSource
SDA1.Update(yourBindingSource.DataSource as DataTable)
No loop required on your grid rows and manually building the InsertCommand and its parameters
For an overview on how a class derived from DbDataAdapter is supposed to work you could read the MSDN reference here
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).
This is my code and I can save only the first item. I need to save the entire list in one database column. Thanks for your help in advance.
Dim mysql As String = "UPDATE tbl_item SET my_item = (#myitems) WHERE id = '" & Label6.Text & "'"
Dim mycmd As New MySqlCommand(mysql, sConnection)
Dim values As New List(Of String)
values.Add(ListBox1.Items.Add(values))
Dim sqlParam As New MySqlParameter With {.ParameterName = "#myitems", .DbType = DbType.String}
mycmd.Parameters.Add(sqlParam)
Dim i As Integer
For i = 0 To values.Count - 1
sqlParam.Value = (ListBox1.Items(i) & ";")
mycmd.ExecuteNonQuery()
Next
Dim i As Integer
For i = 0 To values.Count - 1
If sqlparam.value = "" Then
sqlparam.value = listbox1.Items(i) & ";"
Else
sqlparam.value = sqlparam.value & listbox.Items(i) & ";"
End If
Next
mycmd.ExecuteNonQuery()
If this code failed, then try to put mycmd.execute.... inside..