Executing delete command on MS-Access through VB.NET does not delete the records - sql

Just trying to delete all rows of an Access table:
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Clear old records from extract table
Dim sqlConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.OleDb.OleDbCommand()
Dim intRC As Integer
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "DELETE * FROM [extract] ;"
cmd.Connection = sqlConnection
sqlConnection.Open()
intRC = cmd.ExecuteNonQuery()
sqlConnection.Close()
MsgBox(intRC)
End Sub
I do not get any errors but it doesn't delete the rows either. There are currently 10 rows in the table and the MsgBox shows 10 each time the button is clicked and there are still 10 rows in the table afterwards.
What am I missing?

Try without the asterisk:
DELETE FROM [extract];
You don't generally supply any columns in a DELETE. You only supply columns that you want to match a row against .. via a WHERE clause afterwards.
There are certain dialects of SQL that let you specify thresholds on what you delete in that part of the query - however, I don't believe Access' dialect does (I could be wrong).

Related

Fill combobox starting from the second record

I Fill My ComboBox1 From Field ( Drivers ) ..with this code all records appears in Combobox1 .. How to make so that the first record does not appear in ComboBox1 .. i want the records to start with the second records in my combobx1 .. the ID numbers are (1-2-3-4-5-6) and so on.
Private Sub Fill_Numeros_Drivers()
Dim InfoAdapter As OleDbDataAdapter
Dim InfoTable As DataSet
ComboBox1.Items.Clear()
Dim Sql As String = "SELECT DISTINCT Drivers From Table1"
InfoAdapter = New OleDbDataAdapter(Sql, Conne)
InfoTable = New DataSet
InfoTable.Clear()
InfoAdapter.Fill(InfoTable, "Table1")
For Each rw As DataRow In InfoTable.Tables("Table1").Rows
ComboBox1.Items.Add(rw(0).ToString())
Next
End Sub
Keep your database objects local so you control their closing and disposing. Using...End Using blocks will do that for you even if there is and error.
I added a field to the query for DriverID. Whatever your Primary Key field is might be appropriate to assure the order of the records. The field in the Order By clause must be in the Select part of the query when DISTINCT is used. This field is downloaded but never used.
The first call to reader.Read reads the first record but nothing is done with it. The second call to reader.Read is now on the second record.
Private Sub Fill_Numeros_Drivers()
Using Conne As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("SELECT DISTINCT Drivers, DriverID From Table1 Order By DriverID", Conne)
Conne.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader
reader.Read() 'Reads the first record
Do While reader.Read
ComboBox1.Items.Add(reader.GetString(0))
Loop
End Using
End Using
End Using
End Sub

Datagridview - Oracle Update error "Dynamic SQL generation failed."

I'm using Datagridview to show me joined records from 2 tables. Data that is showing is from one of the tables + data that are in joined table (Table3). SQL query returns results in Datagridview (works fine in Oracle too), but update fails with "Dynamic SQL generation failed. Either no base tables were found or more than one base table was found". Here is my table design:
Table1:
ID_TABLE1
ITEM_NAME
ITEM_DESCRIPTION
Table3: (this is a joined view for Table1 and Table2)
ID_TABLE3
ID_TABLE1_FK
ID_TABLE3_FK
VALIDITY
DATE_CONNECTION
My code (exactly as Oracle recommends):
Public Class Form2
Private da As OracleDataAdapter
Private cb As OracleCommandBuilder
Private ds As DataSet
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Saving.Enabled = False 'this deals with error with updating (from Oracle site)
Dim SQL As String = "SELECT ID_TABLE1, ID_TABLE3, SERIAL_NO, ITEM_NAME, ITEM_DESCRIPTION, VALIDITY, DATE_CONNECTION from TABLE1, TABLE2 WHERE TABLE3.ID_TABLE1_FK=" & Form1.DataGridView1.CurrentRow.Cells(0).Value.ToString
Try
Oracleconn() 'connection to my DB
Dim cmd = New OracleCommand(SQL, Oracleconn)
cmd.CommandType = CommandType.Text
da = New OracleDataAdapter(cmd)
cb = New OracleCommandBuilder(da)
ds = New DataSet()
da.Fill(ds)
My_DGV.DataSource = ds.Tables(0)
Saving.Enabled = True
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'No closing of connection here because of working with Dataset (Oracle suggestion)
End Try
End Sub
Private Sub Saving
da.Update(ds.Tables(0))
Saving.Enabled = True
End Sub
End Class
So, Is my SQL query wrong or what ? Any help would be much appreciated !
P.S.: In actual case only column "VALIDITY" from Table3 will be allowed to change for users, so I need to update only that field.
This is too complicated for me, looks like Oracle-provided suggestion for working with Datasets just isn't easy when you want to perform Update on join table records. So I tried a different approach and It worked for me. Since what I need is to update only 1 column from SQL query which returns to Datagridview I did this :
For Each row As DataGridViewRow In My_.Rows
cmd.Parameters.Add(New OracleParameter("validity", row.Cells(6).Value))
cmd.CommandText = "UPDATE TABLE3 SET VALIDITY= : validity WHERE ID_TABLE1_FK='" & row.Cells(1).Value & "'"
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
If anyone knows the answer to my original question - so how to do same with just da.Update(ds.Tables(0)), then please let me know. I reckon that SQL query needs to be properly changed, using JOIN method.

How to write query based on datagridview results?

Hi I have a query which populates a datagridview which all works correctly. When the datagrid has been populated it has the following columns
UserID
UserName
UserDepot
I have a button which when pressed I would like to run another query based on the information in column UserID and whatever row is selected. I am having difficulty writing this query as I dont know what command I need to write in order to call this information
the datagrid is called dg_usersearch so I was expecting to use something like dg_usersearch.selectedvalue but selectedvalue isnt a member of datagridview does anyone know what command I should be using?
The query for filling the datagrid is as follows
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'creates a list of all incidents as per the search parameters
Dim dt As New DataTable
Dim query As String = "select [userid],[username],[userdepot] from [tbluser]"
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyDATASOURCE")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
'checks to make sure query has results
If dt.Rows.Count > 0 Then
dgusersearch.DataSource = dt
'if no results display the following message
ElseIf dt.Rows.Count = 0 Then
MsgBox(Prompt:="No results for search request, please try again")
End If
Answered by #Plutronix above,
myDGV.SelectedRows(0).Cells(0).Value.ToString()

Error while deleting record from database

I need some help with delete record from database.
I am trying to delete a record from a table in my SQL Server database.
Am I missing something?
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
_DataSet.Tables(0).Rows(CInt(txtCurrent.Text) - 1).Delete()
' tho, it can remove the deleted rows
' we cannot call the DataSet.AcceptChanges method
' because the DataAdapter would not recognize the delete row
' by the time DataAdapter.Update(DataSet) is called.
EnableNavigation()
cmdSave.Enabled = True ' let user update the underlying database
' after deleting the current record, the current record still points to the
' deleted record (though it cannot be updated).
' The user must MoveNext/Back to view other records.
End Sub
DataRow.Delete does not delete this row from database. It marks the DataRow's RowState as deleted. This will be checked from a DataAdapter if you call Update. If it's state is Deleted it will look for its according DeleteCommand which you have to provide.
So you need to provide a DeleteCommand for your DataAdapter which is the sql to delete the row from the database.
You want to Delete it
_DataSet.Tables(0).Rows(CInt(txtCurrent.Text) - 1).Delete()
Dim adapter As New SqlDataAdapter
Dim cmdBuilder As New SqlCommandBuilder(adapter)
Dim DutyDetails As String = "SELECT * from MyTable"
adapter.SelectCommand = New SqlCommand(DutyDetails, SQLConn)
adapter.UpdateCommand = cmdBuilder.GetUpdateCommand
adapter.DeleteCommand = cmdBuilder.GetDeleteCommand
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter.Update(_DataSet.Tables("0"))
Source: Deleting a record from dataset and sql server
You refer to the table as _DataSet.Tables(0), then refer to it later as _DataSet.Tables("0") I bet one of the two is incorrect.

VB.NET 2010 database search

I have a ms access database connected to my vb application through the data wizard.
i want to allow the user to search the database and display their results on a datagrid.
for example user searches for 50 – 55 year Old man under 1.8 meters in height
so far i can display the total amount of people on the database with this code
Private Sub lblTotalPeople_Click(sender As System.Object, e As System.EventArgs) Handles lblTotalPeople.Click
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\AssignmentDatabase.accdb")
' Use wildcard'
Dim cmd As OleDbCommand = New OleDbCommand("Select COUNT(*) From Table1", con)
'' or Where username='" & TextBox1.Text & "'
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Table1")
DataGridView2.DataSource = myDataSet.Tables("Table1").DefaultView
End Sub
how would i search the database based on what the user searches or what would i use?
Assuming you don't already you need to learn how to use SQL.
In your code above the SQL statement is
Select COUNT(*) From Table1
You would need to replace this SQL with a search that uses a value from the user (most likely from a textbox). This text
'' or Where username='" & TextBox1.Text & "'
appears to be part way to some SQL that may work but it looks dangerous. You should also research SQL Injection as using this directly means users could access/damage your Access database.