Unable to read new records from a table - sql

I have a data adapter with 4 tables in a dataset. When I update a new record to the table it appears in the SQL database and the associated datagridivew has been reloaded with the dat in the table, but when I try and read the new record using the following code it can't find the record.
Dim row As DataRow = dsSrvAV.Tables("ServiceAvailability").Select("ID = " & intRecordID).FirstOrDefault()
The same code is used to read other records that were in the database when the application opened, it's just new records that it can't read.
This is the code that writes the new records
Dim newAvailability As DataRow = dsSrvAV.Tables("ServiceAvailability").NewRow()
'Add some data to it
newAvailability("Service_ID") = cboServices.SelectedValue
newAvailability("Date") = Format(dtpDate.Value.ToString, "Short Date")
newAvailability("Downtime") = nudDowntime.Value
newAvailability("Notes") = txtNotes.Text
newAvailability("MajorIncident") = txtMajorIncident.Text
newAvailability("ActionsTaken") = txtActionsTaken.Text
newAvailability("Type") = cboType.SelectedValue
newAvailability("Root_Cause") = txtRootCause.Text
'Add it to the table
dsSrvAV.Tables("ServiceAvailability").Rows.Add(newAvailability)
'Update the adapter
daSrvAv.Update(dsSrvAV, "ServiceAvailability")
dsSrvAV.Tables("ServiceAvailability").AcceptChanges()
Can anyone offer any thoughts as to why this won't allow new records to be read back.
Thanks
Rich

Per comments - this solved the issue.
Close your dsSrvAv dataset, and then re-open it, and then do the select.
Regardng performance: are you adding 1 record per second of 1,000,000. If its 1,000,000 then yes there's an overhead. If its 1 per second there isn't any noticable overhead.

Related

Access SQL Randomizer Not working as intended

I'm using the below mentioned code to select a record ID from an Access Database that wasn't already selected in the last day and add it to an array.
The general goal is that a record that matches the initial "Difficulty" criteria will be retrieved so long as either the record was never selected before OR the record wasn't chosen in the last 2 days. After the loop is done, I should have x amount of unique record ID's and add those onto an array for processing elsewhere.
Private Function RetrieveQuestionID(questionCount As Integer)
' We're using this retrieve the question id's from the database that fit our arrangements.
Dim intQuestArray(0 To questionCount) As Integer
Dim QuestionConnection As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = |DataDirectory|\Database\MillionaireDB.accdb;")
QuestionConnection.Open()
For i As Integer = 1 To intNoOfQuestions
'TODO: If there are no valid questions, pull up any of them that meets the difficulty requirement....
Dim QuestionConnectionQuery As New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) AND (((Questions.LastDateRevealed) Is Null)) OR (Questions.LastDateRevealed >= DateAdd('d',-2,Date())) ORDER BY Rnd((Questions.QuestionID) * Time());", QuestionConnection)
QuestionConnectionQuery.Parameters.AddWithValue("?", intQuestionDifficulty(i - 1).ToString)
Dim QuestionDataAdapter As New OleDb.OleDbDataAdapter(QuestionConnectionQuery)
Dim QuestionDataSet As New DataSet
QuestionDataAdapter.Fill(QuestionDataSet, "Questions")
intQuestArray(i - 1) = QuestionDataSet.Tables("Questions").Rows(0).Item(0)
Dim QuestionConnectionUpdateQuery As New OleDb.OleDbCommand("UPDATE Questions SET Questions.LastDateRevealed = NOW() WHERE Questions.QuestionID = [?]", QuestionConnection)
QuestionConnectionUpdateQuery.Parameters.AddWithValue("?", intQuestArray(i - 1).ToString)
QuestionConnectionUpdateQuery.ExecuteNonQuery()
Next
QuestionConnection.Close()
Return intQuestArray
End Function
However, looping through the array will show that there are records are somehow being repeated even though the record updates during the loop.
Is there another way to loop through the database and pull up these records? I even attempted to move the .Open() and .Close() statements to within the For...Next loop and I'm given worse results than before.
As Steve wrote, the >= should be a < .
In addition, your WHERE clause is missing parentheses around the OR part.
It should be (without all unnecessary parentheses):
SELECT Questions.QuestionID
FROM Questions
WHERE Questions.QuestionDifficulty=[?]
AND ( Questions.LastDateRevealed Is Null
OR Questions.LastDateRevealed < DateAdd('d',-2,Date()) )
ORDER BY Rnd(Questions.QuestionID * Time());
Also have a look at How to get random record from MS Access database - it is suggested to use a negative value as parameter for Rnd().

Save all items of Listbox to access Database Table in VB.Net

I am working on a project and have hit a brick wall again. I have a listbox with some math operations in it (i.e. "1+2=3"). I am trying to save all items in the listbox to an access database, and I think I am getting close. The database has two entries I put in manually, but when I use the following code I only get -1's (plus the two manual entries) in the listbox (when I clear the listbox and load the database into the listbox). The other issue is I need to limit the database to 10 rows which I have no idea how to do. What I would like to do is check the database each time I save to it to see how many rows it has. If the number of listbox items I am saving will exceed 10 rows in the database then clear the database and start from 0 rows. Here is the code I have (which only attempts to save to database):
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = Mathops.accdb; Persist Security Info=False;"
Dim cmd As New OleDbCommand
Dim var1 As String
con.Open()
cmd.Connection = con
Try
For i As Integer = 0 To lstDisplay.Items.Count - 1
var1 = lstDisplay.Items.Item(i).ToString
cmd.CommandText = ("INSERT into Records (Operations) VALUES(" + var1 + ")")
cmd.ExecuteNonQuery()
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
Thank you for any assistance you can provide!
John
Oh...and the database has 2 fields; ID and Operations where ID is the Primary Key.
Try using listdisplay.items(i) to get the text from your listbox.
Then to sort out the 10 items issue:
If you do an SQL query:
SELECT Max(id) FROM Records that will give you the biggest id value in the table
Then check if the value you get back >= 10, and if it is use the SQL:
DELETE FROM Records to clear the table.

Filter and Merge Dataset in Vb.Net

I am working on VS 2010 - Vb.Net, Having a syntax clarification on Filter & Merge DataSet
My dataset - ds has 23 tables. In which, i need to filter one Table with certain criteria.
tempDs.Merge(ds.Tables("p_tree_categories").Select( "GROUP_CODE <> 'PA.43.948'"))
On writing Merge Syntax,
I am able to see only selected table : p_tree_categories in the tempDs. We need the remaining 22 tables along with the filtered record of p_tree_categories.
How can i achieve this ?
It sounds like you only want the filtered rows of table p_tree_categories. This being the case, I would:
Generate a copy of the p_tree_categories which only contains the rows you are interested in.
Remove the existing p_tree_categories from tempDs.
Merge the copy into tempDs as p_tree_categories.
These steps could be implemented something like this:
Dim originalTable As DataTable = tempDs.Tables("p_tree_categories")
Dim filterView As DataView = New DataView(originalTable)
filterView.RowFilter = "GROUP_CODE <> 'PA.43.948'"
Dim filteredTable As DataTable = filterView.ToTable
filteredTable.TableName = "p_tree_categories"
' Remove old, add the new.
tempDs.Tables.Remove(originalTable)
tempDs.Tables.Add(filteredTable)

Sort a Dataset in visualbasic

I don't know what i doing wrong. I have been on several forums trying to figure out how to sort a table in visual basic.
I have treid with and with out a dataview, but noting seams to work.
I have a logg that the user can do new inserts in. It has 3 columns. "Date", "Tool", "Comment".
When my VB application loads the program reads the table from a Access database and i get my sorting just fine by the sql phrase:
"select * from Logg ORDER BY Logg.Datum DESC"
After a user have uppdated the table i whant to sort it again. I have treid the following, but nothing happens. The order is the same whatever i do.
DS is my Dataset and dw my dataview, and "Datum" the column i whant to sort
DS.Tables("hela").DefaultView.Sort = "Datum DESC"
dw = DS.Tables("hela").DefaultView
For i = 0 To antal_poss - 1
LOGG(i, 0) = dw.Table.Rows(i).Item(3)
LOGG(i, 1) = dw.Table.Rows(i).Item(1)
LOGG(i, 2) = dw.Table.Rows(i).Item(4)
Next i
What am i doing wrong?
In your code you use the DataView to retrieve the Table and then the DataRows, but you extract them following the order on the DataTable.
You need to loop following the order of the DataView.
Something like this
Dim i As Integer = 0
For Each row As DataRowView in dw
LOGG(i, 0) = row.Item(3)
LOGG(i, 1) = row.Item(1)
LOGG(i, 2) = row.Item(4)
i += 1
Next i
Of course this assume that your LOGG array contains enough entries to accomodate every row retrieved. It is the same number of the rows in the DataTable

Concurrency violation - the UpdateCommand affected 0 of the expected 1 records

I am working on a VB.NET project and I am trying to Insert / Update some rows in the SQL DB.
To do this I use the code below to bring back a dataset based on 3 parameters.
If the dataset brings no data back, then the code simply inserts a new row.
This works fine.
However, if the data brings a row back (meaning the row already exists in the table) then I want to update one of the values instead.
This is where I'm getting the error in the title of this post.
Can anyone help me with where I'm going wrong please?
Thank you in advance.
Dim x_Update As Boolean
AdaptSql = New Data.AdapterX(SQL_ConnectionString)
DS = New DatsetX
AdaptSql.Fill(DS, Number, PeriodID, TypeID)
If DS.tbl_A.Count > 0 Then
x_Row = DS.tbl_A(0)
x_Row.BeginEdit()
x_Update = True
Else
x_Row = DS.tbl_A.NewRow
End If
x_Row.Number = Number
x_Row.DateID = PeriodID
x_Row.TypeID = TypeID
x_Row.Value = Value
x_Row.UpdatedDate = Date.Now
If x_Update = False Then DS.tbl_A.Addtbl_ARow(x_Row)
x_Row.EndEdit()
AdaptSql.Update(DS)
x_Row = Nothing
DS.Dispose()
AdaptSql = Nothing
check the x_Row.RowState before call AdaptSql.Update(DS), for a newly created row, the row state should be "Added", while an existing record should have "Modified" since there was some updates to it.