Add Data in Access using VB - mysql

I was trying to make a program in VB that accepts user information then saves it in MS access. I already connected MS access and Visual Basic ... The Code Works but it does not add the values inputted by the user in the MS access Table..
Public Sub AddNewStudent()
Dim firstname, middlename As String
con.Open()
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\user.mdf;Integrated Security=True;user Instance=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO Students(FirstName, MiddleName, LastName, Address, Cellphone Number, Course)" & _
"VALUES(" & Me.firstnameTB.Text & ",'" & Me.midnameTB.Text & "')"
firstname = firstnameTB.Text
middlename = midnameTB.Text
Try
mycommand.Parameters.AddWithValue("#firstname", SqlDbType.NVarChar).Value = Me.firstnameTB.Text()
mycommand.Parameters.Add("#middlename", SqlDbType.NVarChar).Value = Me.midnameTB.Text
mycommand.Parameters.Add("#lastnameTB", SqlDbType.NVarChar).Value = Me.lastnameTB.Text
mycommand.Parameters.Add("#addressTB", SqlDbType.NVarChar).Value = Me.addressTB.Text
mycommand.Parameters.Add("#cpnumTB", SqlDbType.NVarChar).Value = Me.cpnumTB.Text
mycommand.Parameters.Add("#courseCB", SqlDbType.NVarChar).Value = Me.courseCB.Text
MsgBox("Successfully added new student")
Catch ex As Exception
MsgBox(ex.Message)
End Try
myconnect.Close()

Firstly, you specify that six columns are to be inserted into but you then only provide two values. Secondly, you add parameters to your command but there are no parameters in your SQL code. You need to provide the same number of values as columns and those values need to be parameters. There are also a couple of other issues, like a column name with a space in it and calling AddWithValue improperly.
Public Sub AddNewStudent()
Dim firstname, middlename As String
con.Open()
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\user.mdf;Integrated Security=True;user Instance=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO Students(FirstName, MiddleName, LastName, Address, [Cellphone Number], Course)" & _
"VALUES(#firstname, middlename, #lastnameTB, #addressTB, #cpnumTB, #courseCB)"
firstname = firstnameTB.Text
middlename = midnameTB.Text
Try
mycommand.Parameters.Add("#firstname", SqlDbType.NVarChar).Value = Me.firstnameTB.Text
mycommand.Parameters.Add("#middlename", SqlDbType.NVarChar).Value = Me.midnameTB.Text
mycommand.Parameters.Add("#lastnameTB", SqlDbType.NVarChar).Value = Me.lastnameTB.Text
mycommand.Parameters.Add("#addressTB", SqlDbType.NVarChar).Value = Me.addressTB.Text
mycommand.Parameters.Add("#cpnumTB", SqlDbType.NVarChar).Value = Me.cpnumTB.Text
mycommand.Parameters.Add("#courseCB", SqlDbType.NVarChar).Value = Me.courseCB.Text
mycommand.ExecuteNonQuery
MsgBox("Successfully added new student")
Catch ex As Exception
MsgBox(ex.Message)
End Try
myconnect.Close()

change the command text like this
mycommand.CommandText = "INSERT INTO Students(FirstName, MiddleName, LastName, Address, [Cellphone Number], Course)" & _
"VALUES(#firstname, #middlename, #lastnameTB, #addressTB, #cpnumTB, #courseCB)"
change all of your lines setting data like this (its more convenient )
mycommand.Parameters.AddWithValue("#courseCB", courseCB.Text)
and finally write this code before
MsgBox("Successfully added new student")
mycommand.ExecuteNonQuery

Related

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.

Displaying multiple values in datagridview by filter searching

I was making a vb program that searches a student info by searching a course.. For example Ajax's course is "BSCS" and DP's course is "BSIT" , then i'm going to select BSCS, so Ajax's must only appear not DP. The result appear's in DataGridView
myConnection.Open()
Dim str As String
str = "SELECT * FROM students WHERE (Course = '" & TextBox1.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
FirstNameTextBox = dr("FirstName")
MiddleNameTextBox = dr("MiddleName")
LastNameTextBox = dr("LastName")
AddressTextBox = dr("Address")
CellphoneNumberTextBox = dr("CellphoneNumber")
CourseTextBox = dr("Course")
End While
myConnection.Close()
Based on your Code you should add new DataGridView to your form and also adding columns with header name that you choose and replace the code with mine
myConnection.Open()
Dim str As String
str = "SELECT * FROM students WHERE (Course = '" & TextBox1.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
DataGridView1.Rows.Add({dr("FirstName"), dr("MiddleName"), dr("LastName"), dr("Address"), dr("CellphoneNumber"), dr("Course")})
End While
myConnection.Close()

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

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.

how can i store the result of the selected columns in my sql query in a variable in vb.net

Try
cn.Open()
Dim query As String
Dim fname As String
Dim reader As MySqlDataReader
query = "Select emp_id,emp_fname,emp_lname,empmname,position,branch from dtrsystem.tblemployee where emp_id = '" & Class1.empid & "' "
sql = New MySqlCommand(query, cn)
reader = sql.ExecuteReader
cn.Close()
Catch ex As Exception
End Try
i want to store my emp_id,emp_fname,emp_lname,empmname,position,branch in a variable and show it in a label. I'm new to vb.net and tried the codes i've searched but it doesnt work. please help
''declare variables v1,v2,v3
Try
cn.Open()
Dim query As String
Dim fname As String
Dim reader As MySqlDataReader
query = "Select emp_id,emp_fname,emp_lname,empmname,position,branch from dtrsystem.tblemployee where emp_id = '" & Class1.empid & "' "
sql = New MySqlCommand(query, cn)
reader = sql.ExecuteReader
while reader.read
v1=reader(0) 'emp id
v2=reader(1) 'emp fname
v3=reader(2) ' emp lname
''etc
End While
cn.Close()
Catch ex As Exception
End Try