How to use if condition using two tables in MySQL - 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.

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

select columns with not null property

I am looking for a way to select columns with a not null property and store it on to an ArrayList.
I have searched many threads for an answer but no luck.
I created a function which allows me to read data from a table but the problem is I don't know how do I get it to read the column name with a not null property. Here is the code that I tried
Public Function getNull(ByVal table As String) As ArrayList
Dim col_names As String = New String(getNames(table))
Dim nullColumns As ArrayList = New ArrayList
Dim dtreader As MySqlDataReader
Dim conn As MySqlConnection
Dim strConn As String
strConn = withDatabase
conn = New MySqlConnection(strConn)
Try
Dim cmd = New MySqlCommand("SELECT * FROM " & table & " WHERE " & col_names & " IS NOT NULL", conn)
conn.Open()
dtreader = cmd.ExecuteReader()
While dtreader.Read
'Get column names with not null property'
End While
Catch ex As Exception
MsgBox("Error " + ex.ToString, MsgBoxStyle.Critical)
End Try
Return nullColumns
End Function
Public Function getNames(ByVal table As String) As String
Dim conn As MySqlConnection
Dim strConn As String
Dim names As New String("")
strConn = withDatabase
conn = New MySqlConnection(strConn)
Using conn
conn.Open()
Dim dt = conn.GetSchema("Columns", New String() {Nothing, Nothing, table})
For Each row In dt.Rows
names += row("COLUMN_NAME") + " AND "
Next
names = names.Remove(names.Length - 4)
End Using
conn.Close()
Return names
End Function
The other threads I found was to find null values in a column, which is not I was looking for.

Visual Basic and Mysql in phpMyadmin [duplicate]

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.

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