Mysql Replace function issue - mysql

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}," & "', ','))"

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

VB.Net - Combobox Not Showing the Data

Combobox2.text not showing the called data from the table. Any help will be appreciated!
Public Sub loadproductdata()
Dim i As Integer
str = "SELECT * FROM tbl_products INNER JOIN tbl_suppliers ON tbl_products.prod_supplier = tbl_suppliers.supp_ID WHERE prod_ID = '" & frm_ProductList.DataGridView1.SelectedRows(i).Cells(0).Value & "'"
cmd = New MySqlCommand(str, con)
con.Open()
dr = cmd.ExecuteReader()
If dr.Read() Then
TextBox1.Text = (dr.Item("prod_code").ToString())
TextBox2.Text = (dr.Item("prod_name").ToString())
ComboBox1.Text = (dr.Item("prod_category").ToString())
Label1.Text = (dr.Item("prod_supplier").ToString())
ComboBox2.Text = (dr.Item("supp_name").ToString())
TextBox3.Text = (dr.Item("prod_purchaseprice").ToString())
TextBox4.Text = (dr.Item("prod_retailprice").ToString())
TextBox5.Text = (dr.Item("prod_discount").ToString())
ComboBox3.Text = (dr.Item("prod_unit").ToString())
TextBox6.Text = (dr.Item("prod_stockqty").ToString())
TextBox7.Text = (dr.Item("prod_reorderlvl").ToString())
TextBox8.Text = (dr.Item("prod_description").ToString())
TextBox9.Text = (dr.Item("prod_remarks").ToString())
End If
con.Close()
End Sub
When a combo box is in DropDownList mode, as yours appears to be, to set its current value to an item from its list you should set the SelectedValue property. You should also consider filling the control with some kind of object that can maintain the difference between a key and a value items, to support a different display value versus backing value (supplier "Microsoft" has ID "6")
While dr.Read()
Dim kvp = new KeyValuePair(Of Integer, String) (0,"")
kvp.Value= (dr.Item("supp_name").ToString())
kvp.Key = DirectCast(dr.Item("supp_id"), Integer)
ComboBox2.Items.Add(kvp)
Loop
Combobox2.DisplayMember = "Value"
Combobox2.ValueMember = "Key"
Now, if you set SelectedValue = 6 in your other query the combo shows "Microsoft"
ps; it's actually a lot easier if you just use a datatable for this:
Dim dt = new DataTable
Dim da as MySqlDataAdapter("SELECT * FROM...", "conn string here")
da.Fill(dt)
'rename your combobox2 to supplierComboBox
supplierComboBox.DataSource = dt
supplierComboBox.DisplayMember = "supp_name"
supplierComboBox.ValueMember = "supp_id"
And it gets easier still if you use strongly typed datasets everywhere instead of this intensely manual yanking data around - but that's out of scope of this question

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

Vb.net Login Session and Mysql Query

I have a login page that i want to collect a users id and use a session to store it so i can use it on the redirect page.
Login Page :
Dim Query As String
Query = "select * from mdxmain.taffiliate where affID = '" & username.Text & "' and affPassword = '" & password.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
Session("affID") = username.Text
HttpContext.Current.Session.Add("affID", userid)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
If count = 1 Then
Response.Redirect("dashboard.aspx")
Else
Literal1.Text = "Invalid credentials"
End If
MysqlConn.Close()
Finally
End Try
MysqlConn.Dispose()
and the dashboard.aspx page that has a query in it :
Dim c As New MySqlConnection("Server=localhost;Database=test;UID=test;PWD=test;")
c.Open()
Dim com As New MySqlCommand("SELECT COUNT(*) as c FROM toutcome WHERE AffID = 'MW0011' AND CompletedDate >= CURDATE();", c)
Dim myReader As MySqlDataReader = com.ExecuteReader(CommandBehavior.CloseConnection)
myReader.Read()
Label1.Text = myReader.Item(0).ToString()
Now what i want to do is the customer logs in using his ID and i want to copy that ID into a session and then use it in the above query (replace MW0011 with the session id) , please help me.
Try to replace the query WHERE AffID = 'MW0011' with WHERE AffID = '" & CType(Session.Item("affID"), String) & "'

How can I save all items in listbox to MYSQL database using vb.net

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