how to save all record show in datagridview to the database - sql

i have this code that will save only the top row of the datagridview,
can someone help me to modify this code so that it will save all the row in datagridview. im using vb 2010 and my database is ms access. thankyou in advance.
Try
Dim cnn As New OleDbConnection(conString)
query = "Insert into tblreportlog(EmpID,empname,department,empdate,timeinaM,timeoutam,lateam,timeinpm,timeoutpm,latepm,thw) values ('" & dgvReport.Item(0, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(1, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(2, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(3, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(4, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(5, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(6, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(7, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(8, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(9, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(10, dgvReport.CurrentRow.Index).Value & "')"
cmd = New OleDbCommand(query, cnn)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
MsgBox("ERROR: " & ErrorToString(), MsgBoxStyle.Critical)
End Try

Working from what is shown and best practices injected, you should be working from a data source such as a DataTable e.g. if when presented the DataGridView to the user there are no rows then create a new DataTable, set the DataTable as the DataSource of the DataGridView then when you are ready to save these rows in the DataGridView cast the DataSource of the DataGridView to a DataTable and use logic similar to the following
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
If dt.Rows.Count > 0 Then
Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
' part field list done here
Using cmd As New OleDb.OleDbCommand With
{
.Connection = cn,
.CommandText = "Insert into tblreportlog(EmpID,empname,department) values (#EmpID,#empname,#department)"
}
' TODO - field names, field types
cmd.Parameters.AddRange(
{
{New OleDb.OleDbParameter With {.ParameterName = "#EmpID", .DbType = DbType.Int32}},
{New OleDb.OleDbParameter With {.ParameterName = "#empname", .DbType = DbType.Int32}},
{New OleDb.OleDbParameter With {.ParameterName = "#department", .DbType = DbType.String}}
}
)
Dim Affected As Integer = 0
cn.Open()
Try
For Each row As DataRow In dt.Rows
' this should not be a auto-incrementing key
cmd.Parameters("#EmpID").Value = row.Field(Of Integer)("FieldName goes here")
cmd.Parameters("#empname").Value = row.Field(Of Integer)("FieldName goes here")
cmd.Parameters("#department").Value = row.Field(Of String)("FieldName goes here")
Affected = cmd.ExecuteNonQuery
If Affected <> 1 Then
Console.WriteLine("Error message, insert failed")
End If
Next
Catch ex As Exception
'
' handle exception
'
' for now
MessageBox.Show("Failed with: " & ex.Message)
' decide to continue or not
End Try
End Using
End Using
End If
On the other hand, if there are new rows with current rows we cast the data source as above then check for new rows along with validation as needed.
For Each row As DataRow In dt.Rows
If row.RowState = DataRowState.Added Then
If Not String.IsNullOrWhiteSpace(row.Field(Of String)("CompanyName")) Then
Other options, utilize a DataAdapter or setup data via data wizards in the ide where a BindingNavigator is setup with a save button.
If it's important to get the new primary key back the method for all methods can do this too.
The following code sample is from this MSDN code sample that shows how to get a new key back using OleDb connection and command.
Public Function AddNewRow(ByVal CompanyName As String, ByVal ContactName As String, ByVal ContactTitle As String, ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Try
Using cn As New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd As New OleDb.OleDbCommand("", cn)
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName,ContactTitle) Values (#CompanyName,#ContactName,#ContactTitle)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName.Trim)
cmd.Parameters.AddWithValue("#ContactName", ContactName.Trim)
cmd.Parameters.AddWithValue("#ContactTitle", ContactTitle.Trim)
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function

Related

MysqlDataReader.Read stuck on the last record and doesnt EOF

i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.

SQL Update not updating records in access

Trying to update the values of Comment and ProgressValue inside a table in access. The message box at the end pops up but none of the values are changed.
Sub UpdateWeeklyReport()
Dim con As OleDbConnection
Dim com As OleDbCommand
con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
com = New OleDbCommand("Update WeeklyReport Set Comment = #Comment, ProgressValue = #ProgressValue Where [EntryDate]='" & CBDate.SelectedValue.ToString & "' AND [AdminNo]=" & CBAdmin.SelectedValue & " AND [ClassCode]='" & CBClass.SelectedItem.ToString & "'", con)
con.Open()
com.Parameters.Add("#Comment", OleDbType.LongVarChar).Value = txtComment.Text
com.Parameters.Add("#ProgressValue", OleDbType.Integer).Value = CBProgress.Text
com.ExecuteNonQuery()
con.Close()
MessageBox.Show("Report Changed")
intialconnection()
End Sub
End Class

SQL Error: "There are no rows at position 0"

I am Trying to create a login form for my software and i keep getting this feedback as error; "There are no rows at postion 0".....This happens whenever i try to add a WHERE clause to my (SLELECT ProfileName, ProfilePassword from Profile) query (i.e 'sqlQuery' in code)......This is a snippet of my code
Public Sub sql_login(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'INITIALIZE YOUR COMMANDS
'IT HOLDS THE DATA TO BE EXECUTED
With cmd
'PASS ON THE VALUE OF CON TO THE MYSQL COMMANND WHICH IS THE CONNECTION
.Connection = con
'THE FUNCTION OF THIS IS TO RETURN THE TEXT REPRESENTED BY A COMMAND OBJECT
.CommandText = sqlQuery
End With
Dim dt = New DataTable
'FOR RETRIEVING AND FILLING DATA IN THE TABLE
Dim da = New SqlDataAdapter(sqlQuery, con)
'NEW TABLE IN THE DATATABLE
da.Fill(dt)
con.Close()
'SET THE TOTAL ROWS OF THE TABLE IN A VARIABLE[MAXROWS]
Dim maxrows As Integer = dt.Rows.Count
con.Close()
'preventing non empty values
If Loginform.UsernameTextBox.Text <> "" And Loginform.PasswordTextBox.Text <> "" Then
If dt IsNot Nothing Then
'CHECKING IF THE TOTAL ROWS OF THE TABLE ARE GREATER THAN 0
If maxrows > 0 Then
'THIS WILL BE NOTIFY YOU THAT WHO WOULD BE THE USER'S
MessageBox.Show("Welcome " & dt.Rows(1).Item(0) & "!" & ControlChars.NewLine & "You have sucessfully logged in.", "Login Confirmation")
'Tracing login time
Try
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT INTO ProfileDates (ProfileName, LoginDates, ProfileID) VALUES ('" & Loginform.UsernameTextBox.Text & "',GetDate(),( SELECT TOP 1 profileID FROM Profile where ProfileName = '" & Loginform.UsernameTextBox.Text & "') )"
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Suppliers_Module.LogoutBtn.Enabled = True
Suppliers_Module.LoginButton.Enabled = False
Catch ex As Exception
con.Close()
MessageBox.Show(ex.Message)
End Try
end if
end if
end if
counting on you for your help. Thanks in advance!

How to update multiple data to Database?

Does anyone knows how to fix this code to and make it work properly?. I want to update my DB that will get the value in Combo box. Is it possible to update 1 or more value at the same time in DB?
CODE
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
Thanks in advance!!
First, you should use sql-parameters instead of string concatenation to prevent possible sql-injection.
Also, your code already updates multiple records if there are more than one with the same yearLevel.
Dim sql = "UPDATE tblStudent SET course = #course,section = #section WHERE yearLevel = #yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("#course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("#course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("#course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
Note that i didn't know the data -type of your columns, so modify it accordingly. I just wanted to show you that it's important to use the correct type in the first place.
This is is for 'INSERTING', however, it can be adapted for 'UPDATING' quite easily:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
source: can be found here
where you have declared field1, and assigned it Combobox2.SelectedValue etc

How to send the entire contents of a listbox to SQL database?

For a listbox loading txt file and now I want to send the contents to sql database in which there are two tables m.in user, comm
http://obrazki.elektroda.pl/8069892000_1409841532.png
How to do to add all items were recorded in the table at the same time with id user?
ex. http://obrazki.elektroda.pl/5048367700_1409841766.png
The following method works only when I select one item.
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Try
con.ConnectionString = "Server = x; User ID = x; Password = x; Database = x;"
con.Open ()
cmd.Connection = con
cmd.CommandText = "insert into ycomm (user, comm) values ​​('" & ListView2.Items (0) .SubItems (0) .Text & "', '" & ListBox1.SelectedItem & "')"
cmd.ExecuteNonQuery ()
Catch ex As Exception
Finally
con.Close ()
End Try
Call showData ()
I found this but dees now work, where is problem?
Replace:
cmd.CommandText = "insert into ycomm (user, comm) values ​​('" _
& ListView2.Items(0).SubItems(0).Text & "', '" & ListBox1.SelectedItem & "')"
With
cmd.CommandText = "INSERT INTO ycomm (user, comm) VALUES(#user, #comm)"
cmd.Parameters.AddWithValue("#user", ListView2.Items(0).SubItems(0).Text)
cmd.Parameters.Add("#comm", SqlDbType.VarChar)
For i As Integer = 0 To lst.Items.Count
cmd.Parameters("#comm").Value = lst.Items(i).Text
cmd.ExecuteNonQuery()
Next