I Have stack Here and does not go
I have a loop that makes connection to database but last 2 days have problem with counting row number. And nowere to find Solution
Dim row as Integer
For i = 100 To 120
Dim DBconn As MySql.Data.MySqlClient.MySqlConnection = New MySql.Data.MySqlClient.MySqlConnection(My.Settings.DBConnStr)
Dim da As MySql.Data.MySqlClient.MySqlDataAdapter
Dim dt As New DataTable
Dim sqlcmd As New MySql.Data.MySqlClient.MySqlCommand
sql = "SELECT Sum(D), Sum(P) FROM fin WHERE K like '" & i.ToString & "%' "
DBconn.Open()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(sql, DBconn)
da.Fill(dt)
DBconn.Close()
row = dt.Rows.Count
MsgBox("i=" & i & " rows=" & row)
dt.Clear()
Next
MSG Box Alway tells me that the RowCount is 1, when manualy i make the query to MYSQL Diferent i Gives me Diferent Rows.
I am sure how you were able to get the dataadapter to fill a datatable. It should be filling a dataset. It should be
DIM ds as New Dataset()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(sql, DBconn)
da.Fill(ds)
DIM rowCount = ds.Table(0).Rows.Count
Try this
DIM rowCount = ds.Tables(0).Select().Count
Related
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
Im a bit confused. I have a mySQL database. It is hashed/encrypted. I used MySqlDataReader and my first query was:
SELECT SUM(column01) FROM dbtest.table01 WHERE column02 = '" & encrypt(selectedValue, salt) & "'
Problem is, the data inside the database is hashed/encrypted that is why it cannot compute the data. Now I switched to MySqlDataAdapter using this query I used in displaying the data in DataGridView(dehashed/decrypted data are displayed here):
SELECT column01 FROM dbtest.table01 WHERE column02 = '" & encrypt(_selectedValue, salt) & "'
Here is my code so far.
Dim dataAdapter As New MySqlDataAdapter
Dim dataTable As New DataTable
Dim bSource As New BindingSource
Try
conn.Open()
Dim query As String
query = "SELECT column01 FROM dbtest.table01 WHERE column02 = '" & encrypt(_selectedValue, salt) & "'"
command = New MySqlCommand(query, conn)
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataTable)
bSource.DataSource = dataTable
DataGridView_Moon.DataSource = bSource
For i As Integer = 0 To dataTable.Rows.Count - 1
dataTable.Rows(i)("column01") = decrypt(dataTable.Rows(i)("column01"), salt)
Next
conn.Close()
Catch ex As Exception
Finally
conn.Dispose()
End Try
If you could, pls place the totalValue into a messagebox. Thanks
I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.
Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next
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