insert multiple data mysql using for loop - mysql

This is the scenario, I have a select query then all fetched data must be inserted into another table.. This is what I came up, I don't know if the for loop does anything.
If I would remove the for loop.
Example:
Fetched data is id1, id2, id3
the inserted data in my database is id1, id1, id1 instead of id1, id2, id3
sql = "SELECT * FROM dummy_violate WHERE res_month <> #month Or res_year <> #year"
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
dr = cmd.ExecuteReader
While dr.Read
id += dr(0)
count += 1
End While
dr.Close()
If count > 0 Then
For i As Integer = 1 To count
sql2 = "INSERT INTO dummy_violate(res_id, res_month, res_year, is_paid)VALUES(#id,#month,#year,#paid)"
cmd = New MySqlCommand(sql2, con)
cmd.Parameters.AddWithValue("#id", id)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
cmd.Parameters.AddWithValue("#paid", 0)
cmd.ExecuteNonQuery()
Next
ElseIf count = 0 Then
MsgBox("Wrong Query")
End If

I don't really understand what you are trying to do and why, it seems that you are simply duplicating the records already present in your table with new records with the same data but with the is_paid flag set to zero. If so just try changing your code in this way:
sql = "SELECT res_id FROM dummy_violate WHERE res_month <> #month Or res_year <> #year"
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
Dim da = new MySqlDataAdapter(cmd)
Dim dt = new DataTable()
da.Fill(dt)
' if we have records to duplicate we have Rows.Count > 0
If dt.Rows.Count > 0 Then
sql2 = "INSERT INTO dummy_violate(res_id, res_month, res_year, is_paid) " & _
"VALUES(#id,#month,#year,#paid)"
cmd = New MySqlCommand(sql2, con)
' Add all the parameters before entering the loop. Just #id changes for every loop,
' so we set it with a dummy value outside the loop and we change it when looping over
' the result table.....
cmd.Parameters.AddWithValue("#id", 0)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
cmd.Parameters.AddWithValue("#paid", 0)
' execute the insert for all the rows count
' rows array starts at zero so loop to count -1
For i As Integer = 0 To dt.Rows.Count - 1
cmd.Parameters("#id").Value = dt.Rows(i)("res_id")
cmd.ExecuteNonQuery()
Next
ElseIf count = 0 Then
MsgBox("Wrong Query")
End If
Remember that if the res_id is a primary key then you cannot insert the records with the same res_id twice. Also, if res_id is an auto_number column (a.k.a. IDENTITY) then you cannot explicitily set its value

Related

Is there a way I can get value from second row first column value in Mysql to a text box in vb.net?

I am trying to solve this mystery from a lot of time. My knowledge is limited. So I got stuck in here. I need to get the value from the second row first column data (Need to specify the row and column and get the value) to a textbox. Please give an answer even this feel easy. Sorry if it is.
Dim conn As SqlConnection
Dim sql As String = "UPDATE attendance.dateverification SET Count1 = CASE WHEN Today_Date <> current_date THEN Count1 + 1 ELSE Count1 END,
Count2 = CASE WHEN Today_Date = current_date THEN Count2 + 1 ELSE Count2 END,
Today_Date = current_date,
Subject_selected =#subject WHERE Subject_Name = #subject; SELECT Subject_Name, Today_Date, Count1, Count2 FROM dateverification"
Try
conn = New MySqlConnection(ConnectionString)
Dim cmd As New MySqlCommand(sql, conn)
cmd.Parameters.Add("#subject", MySqlDbType.VarString, 50).Value = TextBox3.Text
conn.Open()
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
rdr.Read()
TextBox2.Text = rdr("Subject_Name").ToString()
Label1.Text = rdr("Today_Date").ToString()
Label2.Text = rdr("Count1").ToString()
Label3.Text = rdr("Count2").ToString()
Catch ex As Exception
MessageBox.Show(ex.Message)
Call rdr.Read() again to advance to the next record.

How can I Count, Compare and Add Values in DataGridView`s Rows?

What do I need in order to be able to Count, Compare and Add values from DataGridView?
This is my line of code for inserting/populating my Datagridview
Sub display()
Dim temp As Double = 0
'count is my ID that counts the number of tickets from 1 and so on - count is also primary key in my database..
Dim lt As String = "select count as Tickets, mname as Movie, mtime as Time, mprice as Price, mimg as Photo from tickets order by count asc" 'add desc for descending order/ asc for ascending (order by vlanme desc)
Dim da As New MySqlDataAdapter(lt, con)
con.Open()
Dim ds As New DataSet
da.Fill(ds, "settings")
da.Dispose()
DataGridView1.DataSource = ds.Tables(0)
con.Close()
End Sub
What I want is to count how many rows my Datagridview has
I also want to compare Values between two Rows
I also want to add Values of the two Rows
I just want to count how many tickets do I have, compare Names of Row(1) and Row(2) and so on and Add the Prices from Row(1) and so on as a total
(I want to do this while not using the .SelectedCell Method because I will count, compare, add them all at once - all the existing data in datagridview)
Thank You!
I have found an answer to this already
Dim bs As New BindingSource
Dim dr As MySqlDataReader
Dim rowcount As Integer = DataGridView1.Rows.Count
Dim moviecount As Integer = 0
Dim price As Integer = 0
For index As Integer = 0 To rowcount
Try
If con.State = ConnectionState.Closed Then
con.Open()
Dim query As String = "select * from tickets where count = '" & index & "'"
Dim cmd As New MySqlCommand(query, con)
dr = cmd.ExecuteReader
While dr.Read
If moviecount = 0 Then
movie = dr.GetString("mname")
moviecount += 1
End If
If moviecount > 0 Then
If movie = dr.GetString("mname") Then
price += dr.GetInt32("mprice")
Else
MsgBox(movie & " has a total sales of : " & price, MsgBoxStyle.Information, "System Checked!")
price = 0
price += dr.GetInt32("mprice")
moviecount = 0
End If
End If
End While
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
Next
MsgBox(movie & " has a total sales of : " & price, MsgBoxStyle.Information, "System Checked!")
dr.getString(" variable from database ") or dr.getInt32(" variable from database ")
this lets you choose which Value from database will be transferred to what ever Varname that you set to String or Int (also which row do you want if you add the loop)

VB.NET MySQL - datatable returns blank row while db has no data

I am trying to search a data in my MySQL table...
Dim cmd As New MySqlCommand
Dim qry As String = "SELECT SUM(amt) FROM fee_payment WHERE roll_no='" + st_roll + "' AND course='" + c_id + "'"
cmd.Connection = conn
cmd.CommandText = qry
Dim dt As New DataTable
Dim dadapter As New MySqlDataAdapter
dadapter.SelectCommand = cmd
dadapter.Fill(dt)
If dt.Rows.Count > 0 Then
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
Dim t_paid = dr("SUM(amt)")
TbDue.Text = tot_fees - t_paid
End While
dr.Close()
End If
Surprisingly the above dt.Rows.Count returns 1 while the table fee_payment has no data.
What should I do ??
There is nothing surprising at all about the result.
An aggregation query with no group by always returns one row. If all rows are filtered out, then most aggregation functions return NULL, although COUNT() and COUNT(DISTINCT) return 0.
This is standard behavior and how all databases work. It is actually quite a convenience under some circumstances.
EDIT:
If you wanted behavior where no rows are returned, just add a group by:
SELECT SUM(amt)
FROM fee_payment
WHERE roll_no = '" + st_roll + "' AND course = '" + c_id + "'
GROUP BY roll_no, course;

Show last row of database MySQL VB.net

How can I show the last row of data in database?
I have this code here but it only shows the first data row in database
Dim cnPodaci AsNew SqlConnection
cnPodaci.ConnectionString = "your connection string"
cnPodaci.Open()
Dim cm AsNew SqlCommand
cm.CommandText = "SELECT * FROM TABLE"
cm.Connection = cnPodaci
Dim dr As SqlDataReader
dr = cm.ExecuteReader
If dr.HasRows Then
dr.Read()
txtBox1.text = dr.Item("ColumnName1")
txtBox2.text = dr.Item("ColumnName2")
dr.Close()
EndIf
cnPodaci.Close()
You may add an "ORDER BY" to your sql. Like
cm.CommandText = "SELECT * FROM TABLE ORDER BY XX desc"
Assuming XX is the name of the column which increases for every new row.
Edit:
consider:
cm.CommandText = "SELECT * FROM TABLE ORDER BY XX desc limit 1"
It will return the last row, having chosen what XX is.

how to clear previous session value to avoid duplicate records insert to mysql

I am inserting new row into gridview using datatable.
I am using session to stored the previous values because dont want to overwrite the previous row with current new row in gridview.
When i click on button click to insert another new row, result show in gridview is able to display one row after another,but in mysql database is inserted with existing row and previous row data which causing duplicate rows.
How to use session to clear the previous row values when i insert another new row?
Below is my code,can anyone guide me what is wrong?
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
lblVisualWarningCode.Visible = False
Dim conString As String = ConfigurationManager.ConnectionStrings("prcConnectionString").ConnectionString
Dim MySql As New MySqlConnection(conString)
Dim cmd As New MySqlCommand("", MySql)
MySql.Open()
cmd.CommandText = "SELECT RepairID FROM tbVisual ORDER BY CAST(RepairID AS UNSIGNED) DESC"
Dim a As String = cmd.ExecuteScalar
Dim str As Integer = a
Dim dt As New DataTable("Visual")
Try
If Session("Visual") Is Nothing Then
dt.Columns.Add("RepairID", GetType(String))
dt.Columns.Add("VisualInspectionErrorCode", GetType(String))
dt.Columns.Add("VisualInspectionActionTaken", GetType(String))
dt.Columns.Add("VisualInspectionComponentLocation", GetType(String))
Else
dt = DirectCast(Session("Visual"), DataTable)
End If
Session("Visual").Clear()'i am not sure where to put this
'lbVisual is listbox
For i As Integer = 0 To lbVisual.Items.Count - 1
str = str + 1
Dim dr As DataRow = dt.NewRow()
dr("RepairID") = str.ToString
dr("VisualInspectionErrorCode") = ddlVisualInspectionErrorCode.SelectedValue
dr("VisualInspectionActionTaken") = tbVisualInspectionActionTaken.Text
dr("VisualInspectionComponentLocation") = lbVisual.Items(i).ToString
dt.Rows.Add(dr)
Next
Catch ex As Exception
Response.Write(ex.Message)
End Try
For Each row As DataRow In dt.Rows
Dim query1 As String = "INSERT INTO tbvisual (RepairID,VisualInspectionErrorCode,VisualInspectionActionTaken,VisualInspectionComponentLocation) " &
"VALUES ('" + row("RepairID") + "','" + row("VisualInspectionErrorCode") + "','" + row("VisualInspectionActionTaken") + "','" + row("VisualInspectionComponentLocation") + "')"
cmd = New MySqlCommand(query1, MySql)
cmd.ExecuteNonQuery()
Next
Session("Visual") = dt
MySql.Close()
gvVisual.DataSource = dt
gvVisual.DataBind()
End Sub
You can create Unique Index on your MYSQL Table to Prevent inserting duplicate rows and write "INSERT IGNORE" mysql query while inserting the data, which will ignores the rows if already exists.
Follow the links below to learn how to create unique Index in MYSQL-
http://www.w3schools.com/sql/sql_unique.asp
Here is the link to learn about "INSERT IGNORE" MYSQL query:-
http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm
Instead of Session("Visual").Clear() use dt.Clear() that is because once your session is created it contains the data table which has both rows and columns.
Now in each iteration you just want column to be preserved and rows to be dropped after after every insert.
dt.Clear() will remove all the rows and thus you'll only have the fresh row for each insert
UPDATE: Code
If Session("Visual") Is Nothing Then
dt.Columns.Add("RepairID", GetType(String))
dt.Columns.Add("VisualInspectionErrorCode", GetType(String))
dt.Columns.Add("VisualInspectionActionTaken", GetType(String))
dt.Columns.Add("VisualInspectionComponentLocation", GetType(String))
Else
dt = DirectCast(Session("Visual"), DataTable)
End If
dt.Clear()
'lbVisual is listbox
For i As Integer = 0 To lbVisual.Items.Count - 1
str = str + 1
Dim dr As DataRow = dt.NewRow()
dr("RepairID") = str.ToString
dr("VisualInspectionErrorCode") = ddlVisualInspectionErrorCode.SelectedValue
dr("VisualInspectionActionTaken") = tbVisualInspectionActionTaken.Text
dr("VisualInspectionComponentLocation") = lbVisual.Items(i).ToString
dt.Rows.Add(dr)
Next