How to insert looping data in Oracle Database using VB.NET - vb.net

Dim cmd = New OracleCommand
For i = 0 To DataGridView1.Rows.Count - 1
Sql = "INSERT INTO TM_EMPLOYEE_INFO (V_EMPLOYEE_NO, "
Sql = Sql & "V_NAME_TRAINEE,N_GENDER,V_COMPANY) "
Sql = Sql & " VALUES('" & DataGridView1.Rows(i).Cells(0).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(1).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(2).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(3).Value & "') "
Next
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Using connection As New OracleConnection("Provider=OraOLEDB.Oracle;Data Source = XE;User ID = MAN_HOUR;Password = FDTP_MAN_HOUR;")
Dim command As New OracleCommand(Sql)
command.Connection = connection
Try
connection.Open()
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
This is my code. I thinks its already okay but when I run the program the vshost.exe message box appeared. Please help me. Thank you very much.

When you use provider OraOLEDB.Oracle you must use OleDbConnection and OleDbCommand. Otherwise you have to use provider Oracle.DataAccess.
Then you must execute the insert inside the loop, not outside. Would be like this:
Using connection As New OleDbConnection("Provider=OraOLEDB.Oracle;Data Source = XE;User ID = MAN_HOUR;Password = FDTP_MAN_HOUR;")
connection.Open()
Dim command As New OleDbCommand()
command.CommandType = CommandType.Text
command.Connection = connection
For i = 0 To DataGridView1.Rows.Count - 1
Sql = "INSERT INTO TM_EMPLOYEE_INFO (V_EMPLOYEE_NO, "
Sql = Sql & "V_NAME_TRAINEE,N_GENDER,V_COMPANY) "
Sql = Sql & " VALUES('" & DataGridView1.Rows(i).Cells(0).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(1).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(2).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(3).Value & "') "
command.CommandText = Sql
Try
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
connection.Close()
End Using
However, this is a bad implementation, better work with bind variables like this:
Using connection As New OleDbConnection("Provider=OraOLEDB.Oracle;Data Source = XE;User ID = MAN_HOUR;Password = FDTP_MAN_HOUR;")
connection.Open()
Dim command As New OleDbCommand()
command.CommandType = CommandType.Text
command.Connection = connection
Sql = "INSERT INTO TM_EMPLOYEE_INFO "
Sql = Sql & "(V_EMPLOYEE_NO, V_NAME_TRAINEE,N_GENDER,V_COMPANY) "
Sql = Sql & "VALUES (?,?,?,?)"
command.CommandText = Sql
command.Parameters.Add("empNo", OleDbType.Integer)
command.Parameters.Add("trainee", OleDbType.VarChar, 100)
command.Parameters.Add("gender", OleDbType.VarChar, 10)
command.Parameters.Add("company", OleDbType.VarChar, 100)
For i = 0 To DataGridView1.Rows.Count - 1
For c = 0 To 4
command.Parameters(c).Value = DataGridView1.Rows(i).Cells(c).Value
Next
Try
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
connection.Close()
End Using

Related

VB.net and mysql data

i'm working an attendance system and its almost done but i have a problem in my time in and time out form. i already did the codes for time in and time out of students and its working quite well but my problem is after the day ends it must reset the data so it can gather a new data when another day starts.
this is my code for time in and out
Dim check As Boolean
Call connect()
Dim cmdd As New MySqlCommand("Select Count(*) from attendance_for_student WHERE Remarks = 'IN' ", dbconn)
Dim i As Integer = cmdd.ExecuteScalar()
cmdd = Nothing
dbconn.Close()
TextBox1 .Text = i
If student.Text = "" Then
MsgBox("Scan Your Code!", MsgBoxStyle.Critical)
Else
Call connect()
sql = "SELECT * FROM student WHERE Sbarcode='" & student.Text & "'"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader
Do While dbread.Read
Dim id As String = student.Text
Dim folder As String = "c:\jpnhs\"
Dim filename As String = System.IO.Path.Combine(folder, id & ".bmp")
PictureBox1.Image = Image.FromFile(filename)
FULLNAME.Text = dbread.Item(1).ToString & " " & dbread.Item(2).ToString & " " & dbread.Item(3).ToString
Loop
dbread.Close()
dbconn.Close()
End If
If Len(student.Text) = 8 Then
Call connect()
check = False
sql = "SELECT * FROM attendance_for_student WHERE Sbarcode = '" & student.Text & "' AND (remarks <>'IN' OR remarks <>'OUT')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader
Do While dbread.Read
check = True
Loop
dbread.Close()
dbconn.Close()
If check = False Then
Call connect()
sql = "INSERT INTO attendance_for_student(Sbarcode,Time,Date,remarks) VALUES ('" & student.Text & "','" & LBLTime.Text & "','" & LBLDate.Text & "','IN')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
dbconn.Close()
Search_Code()
Else
Call connect()
sql = "INSERT INTO attendance_for_student(Sbarcode,Time,Date,remarks) VALUES ('" & student.Text & "','" & LBLTime.Text & "','" & LBLDate.Text & "','OUT')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
dbconn.Close()
Search_Code()
End If
End If

Student attendance time in time out

i made a student attendance system using barcode scanner and its already working the time in time out works well but my problem is this after the student scan his/her barcode for time out the next time he/she scan his/her barcode the remarks should be time in but my code only sticks with a time out remarks.
this is my code for time in time out
Dim check As Boolean
Call connect()
Dim cmdd As New MySqlCommand("Select Count(*) from attendance_for_student WHERE Remarks = 'IN' ", dbconn)
Dim i As Integer = cmdd.ExecuteScalar()
cmdd = Nothing
dbconn.Close()
TextBox1 .Text = i
If student.Text = "" Then
MsgBox("Scan Your Code!", MsgBoxStyle.Critical)
Else
Call connect()
sql = "SELECT * FROM student WHERE Sbarcode='" & student.Text & "'"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader
Do While dbread.Read
Dim id As String = student.Text
Dim folder As String = "c:\jpnhs\"
Dim filename As String = System.IO.Path.Combine(folder, id & ".bmp")
PictureBox1.Image = Image.FromFile(filename)
FULLNAME.Text = dbread.Item(1).ToString & " " & dbread.Item(2).ToString & " " & dbread.Item(3).ToString
Loop
dbread.Close()
dbconn.Close()
End If
If Len(student.Text) = 8 Then
Call connect()
check = False
sql = "SELECT * FROM attendance_for_student WHERE Sbarcode = '" & student.Text & "' AND (remarks <>'IN' OR remarks <>'OUT')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader
Do While dbread.Read
check = True
Loop
dbread.Close()
dbconn.Close()
If check = False Then
Call connect()
sql = "INSERT INTO attendance_for_student(Sbarcode,Time,Date,remarks) VALUES ('" & student.Text & "','" & LBLTime.Text & "','" & LBLDate.Text & "','IN')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
dbconn.Close()
Search_Code()
Else
Call connect()
sql = "INSERT INTO attendance_for_student(Sbarcode,Time,Date,remarks) VALUES ('" & student.Text & "','" & LBLTime.Text & "','" & LBLDate.Text & "','OUT')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
dbconn.Close()
Search_Code()
End If
End If

Updating DataGridView date cell to database mismatch error Vb.net

first, I would like to say that thank all of the programmers, people that make this website so efficient! I'm proud to say that 80% of my programming knowledge on VB I gained was because of all of the samples and answers in this webpage. Anyway, so I'm developing a Quality Control application for my company and there's a datagridview in one of my forms. The user can make changes to it and after that he/she has to save the datagrid back to the MS Access database. I tried everything and I can't save the date field into the database. I checked for field formatting and the database table is formatted to "Date/time"
here is what i have:
Dim sql As String
Try
For i As Integer = 0 To dataAddemdumView.RowCount - 1
sql = "UPDATE MasterRecordsT SET Fecha = '" & dataAddemdumView.Rows(i).Cells("Fecha").Value & "', Pass = " & dataAddemdumView.Rows(i).Cells("Pass").Value & ", Fail =
" & dataAddemdumView.Rows(i).Cells("Fail").Value & ", Employee = " & dataAddemdumView.Rows(i).Cells("Employee").Value & ", Gig = " & dataAddemdumView.Rows(i).Cells("Gig").Value & ", GigNotes =
'" & dataAddemdumView.Rows(i).Cells("GigNotes").Value & "', Department = '" & dataAddemdumView.Rows(i).Cells("Department").Value & "' WHERE ID = " & dataAddemdumView.Rows(i).Cells("ID").Value & ""
cmd = New OleDbCommand(sql, con)
con.Open()
da.UpdateCommand = con.CreateCommand()
da.UpdateCommand.CommandText = sql
da.UpdateCommand.ExecuteNonQuery()
con.Close()
Next
Catch ex As Exception
con.Close()
'MessageBox.Show("OPEX Quality encountered a problem, Try to reopen the application to solve issues", "Error 0002", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
thank you so much for your help guys!
so this would be the final code and it works
Dim sql As String
Try
For i As Integer = 0 To dataAddemdumView.RowCount - 1
If Not dataAddemdumView.Rows(i).Cells("Fecha").Value Is DBNull.Value Then
sql = "UPDATE MasterRecordsT SET Fecha = '" & dataAddemdumView.Item("Fecha", i).Value & "', Pass = " & dataAddemdumView.Rows(i).Cells("Pass").Value & ", Fail =
" & dataAddemdumView.Rows(i).Cells("Fail").Value & ", Employee = " & dataAddemdumView.Rows(i).Cells("Employee").Value & ", Gig = " & dataAddemdumView.Rows(i).Cells("Gig").Value & ", GigNotes =
'" & dataAddemdumView.Rows(i).Cells("GigNotes").Value & "', Department = '" & dataAddemdumView.Rows(i).Cells("Department").Value & "' WHERE ID = " & dataAddemdumView.Rows(i).Cells("ID").Value & ""
cmd = New OleDbCommand(sql, con)
con.Open()
da.UpdateCommand = con.CreateCommand()
da.UpdateCommand.CommandText = sql
da.UpdateCommand.ExecuteNonQuery()
con.Close()
End If
Next
Catch ex As Exception
con.Close()
MsgBox(ex.Message)
'MessageBox.Show("OPEX Quality encountered a problem, Try to reopen the application to solve issues", "Error 0002", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Searching multiple tables in Access vb.net

I have a search button which looks up for data only in tblDopage but there is a field strMatrice in this table that is linked to table tblMatrice. So if the user is searching for Matrice I should retrieve Matrice from tblMatrice and innerjoin it with tblDopage on strMatrice, it's like a search inside search and the result of searching for matrice is more than 1 result so that I have many results which i should link them with tblDopage to display the final result. What shall i do, I spended 3 days searching for a solution.
I retrieved strMatrice from tblMatrice and populated a dataset with the result but I don't know how to innerjoin between a dataset and table in the database which is the tblDopage
Help is very appreciated, Thank you in advance
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim sql = "SELECT * from tblDopages WHERE "
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
'if referentiel is enabled
myConnection.Close()
If CKBnomref.Checked Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'Get IDref from table tblRefMatDetails and then make an innerjoin with tblRefMatrice to retrieve the matrice and insert it into the search query of tblDopages
Dim query = "select distinct a.strMatrice from tblRefMatrice a INNER JOIN tblRefMatDetails b on a.intIDref=b.intIDRef where "
cmd = New OleDbCommand(query, myConnection)
Try
If CKBnomref.Checked Then
query = query & "b.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
query = query & "b.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
query = query & "b.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
query = query & "b.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
query = query & "b.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
' Remove the last AND if any ....'
If query.EndsWith(" AND ") Then
query = query.Substring(0, query.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If query.EndsWith(" WHERE ") Then
query = query.Substring(0, query.Length - 7)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.CommandText = query
cmd.Connection = myConnection
Dim MyDataTable As New DataTable
Dim da As New OleDbDataAdapter(query, myConnection)
da.Fill(MyDataTable)
Dim row As DataRow
For Each row In MyDataTable.Rows
Dim strMatrice As String
strMatrice = row("strMatrice")
Next row
DataGridView2.DataSource = MyDataTable
'to focus on first row of DGV after populating it
DataGridView2.Rows(0).Selected = True
myConnection.Close()
Dim matrice As String
For x As Integer = 0 To DataGridView2.Rows.Count - 2
matrice = DataGridView2.Rows(x).Cells(0).Value
sql = sql & " strMatrice = '" & matrice.ToString & "' AND "
Dim row As DataRow
For Each row As DataRow In MyDataTable.Rows
matrice = row.Item("Detail")
Next row
Next
End If
' Remove the last AND if any ....'
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1

updating a sql 2005 database using text boxes in vb.net

I have a VB.Net form which allows the user to update the customer details such as name, contact no:, etc. So when the customer enters the new name for the customer name etc. the application should update the corresponding field in the existing entry that relates to the customer ID.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = " UPDATE TblCustomerDetails (compID, compName, compContact, compAddress, compFax, compEmail, compPayterm, compTaxscheme, compPaymode, compRemarks ) SET Values ('" & lblCID.Text & "', '" & txtCname.Text & "', '" & txtCpno.Text & "', '" & txtCaddrs.Text & "','" & txtCfax.Text & "', '" & txtCemail.Text & "', '" & cmbPterm.Text & "','" & cmbTaxschm.Text & "',' " & cmbPmode.Text & "', '" & txtRemarks.Text & "') WHERE compID = '" & lblCID.Text & "';"
cmd.ExecuteNonQuery()
MsgBox("Account updated!!", MsgBoxStyle.Information, "Updation complete")
Your using a INSERT syntax for your UPDATE statement. Your UPDATE statement should have the form:
UPDATE tableName
SET col1 = val1,
col2 = val2,
col3 = val3
WHERE someColumn = someValue
Additionally, you are wide open to SQL Injection attacks by using non-parameterized queries. Finally, I would use a Using blocks to ensure your connection and command are properly closed and disposed of.
Putting it all together it would look something like this:
Using Dim cn As SqlConnection = New SqlConnection("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
Dim sqlQuery As String = "UPDATE TblCustomerDetails " + _
"SET compName = #compName, " + _
"compContact = #compContact, " + _
"compAddress = #compAddress, " + _
"compFax = #compFax, " + _
"compEmail = #compEmail, " + _
"compPayterm = #compPayterm, " + _
"compTaxscheme = #compTaxscheme, " + _
"compPaymode = #compPaymode, " + _
"compRemarks = #compRemarks " + _
"WHERE compID = #compID"
Using Dim cmd As SqlCommand = New SqlCommand(sqlQuery, cn)
cmd.Parameters.AddWithValue("#compFax", txtCname.Text)
cmd.Parameters.AddWithValue("#compContact", txtCpno.Text)
cmd.Parameters.AddWithValue("#compAddress", txtCaddrs.Text)
cmd.Parameters.AddWithValue("#compFax", txtCfax.Text)
cmd.Parameters.AddWithValue("#compEmail", txtCemail.Text)
cmd.Parameters.AddWithValue("#compPayterm", cmbPTerm.Text)
cmd.Parameters.AddWithValue("#compTaxscheme", cmbTaxschm.Text)
cmd.Parameters.AddWithValue("#compPaymode", cmbPmode.Text)
cmd.Parameters.AddWithValue("#compRemarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#compID", lblCID.Text)
Dim result As Integer
result = cmd.ExecuteNonQuery()
If result = 1 Then
MsgBox("Account updated!!", MsgBoxStyle.Information, _
"Updation complete")
Else
MsgBox("Account not updated!!", MsgBoxStyle.Information, _
"Updation not complete")
End If
End Using
End Using
There are a few more things to note in the above code sample:
First, I removed compID from the list of values to update. You're using that in your WHERE query, so I think you would have interesting results in your query if you're trying to update the same column you are using as part of your WHERE clause. Additionally, the source for that value is a Label, which tells me it's not supposed to be changed.
Secondly, ExecuteNonQuery() returns an int with the number of rows affected. In this case, it should be 1 - if it's not 1, I have you show a different message box.
Thirdly, cmbPTerm, cmbTaxxshm and cmbPmode sound like ComboBox to me, and you're not going to get what I think you're expecting using their Text property. I think you'll want SelectedText - hard to say without knowning how your ComboBoxes are bound. I'll leave that as an exercise for you :)
Fourth, I broke the UPDATE query up across several lines simply for readability - you don't have to do it that way, as long as the query is correct.
Finally, I'd suggest using MessagBox.Show() vs MsgBox.
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand
cnn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "update TblCustomerDetails set compName='" & txtCname.Text & "' , compContact = '" & txtCpno.Text & "' , compAddress = '" & txtCaddrs.Text & "' , compFax = '" & txtCfax.Text & "' , compEmail = '" & txtCemail.Text & "' , compPayterm = '" & cmbPterm.Text & "' , compTaxscheme = '" & cmbTaxschm.Text & "' , compPaymode = '" & cmbPmode.Text & "' , compRemarks = '" & txtRemarks.Text & "' where compID = '" & lblCID.Text & "'"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("entry updated!!!")