Visual Basic and Mysql in phpMyadmin [duplicate] - mysql

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.

Related

Get Result from mysql by vb.net

I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using

Save Datagridview if it is Checked by CheckboxColumn

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

How to use if condition using two tables in MySQL

Can anyone help me on this? What I wanted to happen is that if the value exist in Table 1 (employee), it will then check Table 2 (mobilelist) if it also exist there. Here's the code:
Private Sub TextBox_IDNumber_LostFocus(sender As Object, e As EventArgs) Handles TextBox_IDNumber.LostFocus
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;password=12345;database=my_db"
Dim READER As MySqlDataReader
Dim READER2 As MySqlDataReader
Dim _isFound As Boolean = False
Dim _isExist As Boolean = False
Try
Mysqlconn.Open()
Dim empmr As String
Dim empml As String
Dim fn1 As String
Dim fn2 As String
Dim ln1 As String
Dim ln2 As String
empmr = "Select * from my_db.employee where IDNumber ='" & TextBox_IDNumber.Text & "'"
empml = "Select * from my_db.mobilelist where IDNumber = '" & TextBox_IDNumber.Text & "' AND DateAssigned is not Null AND DateReturned is Null"
Command = New MySqlCommand(empmr, Mysqlconn)
READER = Command.ExecuteReader
While READER.Read()
_isFound = True
fn1 = READER.GetString("FirstName")
ln1 = READER.GetString("LastName")
End While
If _isFound Then
TextBox_FirstName.Text = fn1
TextBox_LastName.Text = ln1
ElseIf Not _isExist Then
MessageBox.Show("Record Not Found in Master Data")
TextBox_IDNumber.Clear()
TextBox_FirstName.Clear()
TextBox_LastName.Clear()
TextBox_IDNumber.Focus()
End If
Catch ex As MySqlException
MessageBox.Show("Error!")
Finally
Mysqlconn.Dispose()
End Try
End Sub
Assuming you have the appropriate Primary Key and Foreign Key relationship between the tables Employee and MobileList you use this query to find records on the MobileList table for an employee:
Dim myQuery as string
myQuery = "SELECT FirstName, LastName, MobileNumber
FROM Employee
JOIN MobileList
ON Employee.IDNumber=MobileList.IDNumber
WHERE Employee.IDNumber=#ID"
Note: You should rename the IDNumber column on the MobileList to avoid confusion.
You should also improve your access to the database with the Using statement and take advantage of Parameters to prevent SQL injection:
Using myConn As New SqlConnection("Your connection string")
myConn.Open()
Using myCmd As New SqlCommand(myQuery, myConn)
myCmd.Parameters.AddWithValue("#ID", "Your ID value")
Using myReader As SqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows Then
'There are mobile numbers issued to that ID'
Do While myReader.Read()
'Iterate through all existing records'
Loop
Else
'There are no mobile numbers issued to that ID'
End If
End Using
End Using
End Using
Keep in mind that this gives you the mobile numbers for a particular employee, it doesn't tell you if a particular employee exists.

Importing contents of text file into MySQL using VB.Net

Good day everyone. I am trying to create a program that will transfer all of the contents of a text file into a database. So far, my code works, but my code only inserts the first line of the text file into the database. What should I add to solve the problem? I am noob at programming sorry.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim Query As String
Dim data As String = System.IO.File.ReadAllText(filename)
Dim Loc, _date, time, temp, id As String
Loc = data.Substring(0, 3)
_date = data.Substring(3, 8)
time = data.Substring(11, 4)
temp = data.Substring(15, 3)
id = data.Substring(18, 3)
Query = "INSERT INTO tbl_entrance_swipe VALUES ('" + Loc + "','" + _date + "','" + time + "','" + temp + "','" + id + "')"
Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
Try
con.Open()
Dim sql As MySqlCommand = New MySqlCommand(Query, con)
sql.ExecuteNonQuery()
MsgBox("Record is Successfully Inserted")
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Record is not Inserted" + ex.Message)
End Try
End Sub
End Class
You are using File.ReadAllText which reads the complete text of the file. You want to read line by line, therefore you can use File.ReadLines(deferred executed) or File.ReadAllLines(reads all into a String()).
You should also use sql-parameters to prevent sql-injection and incorrect implicit type conversions or localization issues. Finally, use the Using statement to ensure that all unmanaged resources are disposed (f.e. the connection gets closed even on error):
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim allLines As String() = File.ReadAllLines(filename)
Dim query As String = "INSERT INTO tbl_entrance_swipe VALUES (#Loc, #Date, #Time, #Temp, #Id)"
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim loc, dt, time, temp, id As String
loc = line.Substring(0, 3)
dt = line.Substring(3, 8)
time = line.Substring(11, 4)
temp = line.Substring(15, 3)
id = line.Substring(18, 3)
cmd.Parameters.Clear()
Dim pLoc As New MySql.Data.MySqlClient.MySqlParameter("#Loc", MySqlDbType.VarChar)
pLoc.Value = loc
cmd.Parameters.Add(pLoc)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.VarChar)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
Dim pTemp As New MySql.Data.MySqlClient.MySqlParameter("#Temp", MySqlDbType.VarChar)
pTemp.Value = temp
cmd.Parameters.Add(pTemp)
Dim pId As New MySql.Data.MySqlClient.MySqlParameter("#Id", MySqlDbType.VarChar)
pId.Value = id
cmd.Parameters.Add(pId)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using

How to populate a datagridview VB.Net

I have queried my MySql database and data is stored in a dataset named Search Events(I have checked this and it works)
However when i try to pass this data into a datagridview and then ultimately my array it doesn't seem to work :( The problem seems to be that no data is being passed from Search Events into Table
Any ideas??
Dim Table As New DataGridView
Table.DataSource = SearchEvents.Tables("Event ID")
Dim EventID(Table.Rows.Count - 1) As String
For i = 0 To 12
EventID(i) = Table.Rows(0).Cells(i).Value
Next
'Try the following function
Public Sub getuserlist()
Dim con As New MySqlConnection(ConnectionString)
Try
If con.State <> ConnectionState.Open Then
con.Open()
End If
Dim selecttaxinv = "SELECT * FROM user_tb WHERE user_status = 'Active' ORDER BY date_registered DESC"
Dim myCommand As New MySqlCommand(selecttaxinv, con)
Dim dr As MySqlDataReader
dr = myCommand.ExecuteReader()
yourdatagridview.Rows.Clear()
Dim b = 1
While dr.Read()
Dim fullname As String = dr("fname") & " " & dr("mname") & " " & dr("lname")
Dim row As String() = New String() {dr("user_id"), b, fullname, dr("fname"), dr("date_registered")}
yourdatagridview.Rows.Add(row) 'print list
b += 1
End While
dr.Close()
If con.State = ConnectionState.Open Then
con.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub