VB.net - How can I delete an Item in an Access Database? - sql

I'm trying to delete an Item in my Access Database with vb.net
my code is:
Dim DString As String = "DELETE * FROM studentTable WHERE ID='" & DataGridView1.SelectedRows.Item(0).Cells(0).Value & "'"
Dim DCMD As New OleDbCommand(DString, con)
DCMD.ExecuteNonQuery()
Fill()
the code is working fine, my Problem is it's not working because my "ID" Row is set to AutoIncrement. What can I do to fix??
King regards

You have a syntax error in your SQL. You do not need a projection (column list) for a DELETE statement.
Try removing the * such as:
DELETE FROM studentTable WHERE ID=....
Also you do not need to quote numeric values with the apostrophe character (I don't think it will hurt).
You might also want to consider using a parameterized query instead of embedding the value.

Related

MS ACCESS VBA: type mismatch error in recordset name into SQL statement string

How should I write the name of the recordset correctly? I have a type mismatch error on & rsg & at "sq3=..." line. Thanks in advance.
Dim rsG As DAO.Recordset
Dim sq2, sq3 As String
sq2 = "SELECT * from GeneralTable "
sq2 = sq2 & "where gsede='LION' and (gExclu is null) and (gAda is null) "
sq2 = sq2 & "order by gnomb,gnif;"
Set rsG = CurrentDb.OpenRecordset(sq2)
sq3 = "UPDATE " & rsG & " SET gsede ='AA' WHERE gsede='LION'"
DoCmd.RunSQL (sq3)
You are mixing up totally different ways to update data - UPDATE SQL and VBA recordset.
If you want to update a recordset row by row, you do something like
Do While Not rsG.EOF
If rsG!foo = "bar" Then
rsG.Edit
rsG!gsede = "AA"
rsG.Update
End If
rsG.MoveNext
Loop
Do the update using a single query:
update generaltable
set gsede = 'AA'
where gsede ='LION' and (gExclu is null) and (gAda is null);
If you do the update off of rsG, then you'll likely do a separate update for each row, and that is inefficient.
You can't mix and match SQL and recordset objects. You can either build a full update statement that includes the logic of the first select (as other answer suggests), or you can open a dynamic recordset and loop through the records programmatically to make the updates.
That being said, looping through large recordsets programmatically to make updates is usually better handled by a bulk SQL statement, unless it is essential to consider each row individually inside the code - which in your basic example would not be the case.
MS has a good article on the DAO.Recordset object. There is a dynamic-type Recordset example about halfway down.

Access 2010 - How to make multiple queries with changing the criteria automatically

I have a question concerning a "serie of queries". After searching the internet for hours, I am really lost!
I want to make 200 queries with changing criteria (the values from the field "City"). How can I tell Access "please repeat the query on the fields "X", "Y" and "Z" by grouping by the field "City". Is there a simple way to make Access pull the Values of "City" from a list and creating a query having the same name like the Value in "City". And doing that for all 200 Cities?
Unfortunately, I am fairly new to Access and VBA. Any help would be HIGHLY APPRECIATED :)
Thanks in advance
A few options. You could open a recordset containing all your Cities, then loop through it and you get a buncha queries:
dim s as string
dim sql as string
dim r as new adodb.recordset
'populate r with SELECT * FROM tblCities (code not shown here)
s = r![City]
sql = "SELECT * FROM tbl1 WHERE City = '" & s & "';"
debug.print sql
'do whatever you want with the contents of sql

Writing Dynamic SQL Statement

I am very new to Microsoft Access.
I would like to select a column from a table based on the value of a parameter (i.e. my table has columns x, y and z and I have a chosencol parameter which is set by the user using a dropdown.
I can select one / all of the columns using a select command, however, I would like to do this using my parameter chosencol instead.
Having read around, I have found a number of references to using the SET and EXEC commands, however, entering them into the SQL command in Access just yields errors.
Please could someone advise me as to how I go about implementing a dynamic-sql query in Access (in fine detail as I think I am writing the commands in the wrong place at the moment...)
First I created an example table in Access.
Next, I created an example form to query your value. The dropdown is called 'chosencol'. Select a value from the Column Select dropdown and press the "Lookup Value" button.
Here is the code under the "Lookup Value" button's On Click event. A SQL statement is dynamically built with the column you chose. The column is renamed to [FieldName] to that it can by referenced.
Private Sub btnLookup_Click()
Dim rsLookup As New ADODB.Recordset
Dim strSQL As String
strSQL = "select " & chosencol.Value & " as [FieldName] from Table1 where ID=1"
rsLookup.Open strSQL, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
If rsLookup.EOF = False Then
txtValue.SetFocus
txtValue.Text = rsLookup![FieldName]
End If
rsLookup.Close
End Sub
When the button is pushed, the value from whatever column you selected will be returned. For this simple example, I'm always returning row 1's data.
I'm pretty sure you can't do that in straight SQL. However, you can create the SQL string in VBA code and save it as a query.
CurrentDB.CreateQueryDef("MyQueryName", "SELECT " & chosencol & " FROM MyTable")
Now, MyQueryName will be a permanent query in your database and can be referenced wherever you want.
If chosencol is a multi-select dropdown, you'll have to read the selected values into an array and then write the array to one concatenated string and use that instead.

Input string was not in a correct format Error Filling a Datatable

I have a table which is all VarChar() fields.
I fill the dataset with the following SQL (using vb.net):
Select * From archive_naerns90_2006_q3.NAERNS90_Calls Where siteid = 'NAERNS90-02-627303'
I get this error:
Input string was not in a correct format.Couldn't store <02-627303> in agencyid Column. Expected type is Double.
When I run this query from PgAdmin it works fine. I am running this same bit of code on dozens of other tables with no problems.
The value 02-627303 referenced in the error is the value in the agencyid column for that record, but there are no Double fields in the table. Full disclosure - there were two, but I changed them from Double to VarChar and neither were the agencyid coplumn.
The other kicker is this only happens on some records in that table.
I am guessing I have some corrupt table. I copied the table, but the copy has the same problem. And Since it works in PgAdmin but not from my code it also may have something to do with npgsql.
Edit: I was asked to add the code around the problem area as this looked like an Insert error. I am not doing any Inserts at all in this function.
SQL = "Select * From " & MlocRow("currentdb") & "." & SubTablesArr(Y) & " Where siteid = '" & DataRow("siteid") & "'"
Adapter.SelectCommand = New NpgsqlCommand(SQL, MLConnect)
Adapter.Fill(subDT)
My ConnectionString is:
"HOST=192.168.0.133;DATABASE=masterlists;USER ID=myuser;PASSWORD=mypassword"
Thanks,
Brad
You can type cast that col to varchar() explicitly...

Using a VBA array in a SQL statement

I am trying to write some code that uses SQL to delete rows from several tables.
A user would type type numbers into a textbox that are separated by a comma which is used in the WHERE clause of a SQL DELETE statement.
I have managed to split the string into a variant array and now I want to insert it into my SQL statement.
How do I insert the variable into the SQL statement and have it run through every element of the array?
EDIT: A bit more digging has taught me about For Each Next statements. This is probably what im looking for.
I suggest you build your query in VBA, then your list of numbers can be an IN statement:
sSQL = "DELETE FROM table WHERE ID In (" & MyList & ")"
Where MyList = "1,2,3,4" or such like.
As you can see, you do not need an array and a textbox would be more suitable than a combobox. If you wish to allow your users to select by say, a name, then a listbox is useful. You can iterate through the selected items in the listbox and build a string from IDs to be used in the Delete statement. ( MS Access 2007 - Cycling through values in a list box to grab id's for a SQL statement )
You can then execute the sql against an instance of a database. For example:
Dim db As Database
Set db = CurrentDB
db.Execute sSQL, dbFailOnError
MsgBox "You deleted " & db.RecordsAffected & " records."
A generic approach
WHERE
','+Array+',' like '%,'+col+',%'
It will consider all the numbers available in your Array
You could make it simple and elaborate a string, something like
stringBuilder sb = StringBuilder("DELETE FROM YOURTABLE WHERE ");
foreach(string st in stringArray){
sb.append("YOURFIELD='" + st + "'");
//If it is not the last element, add an "OR"
if (st != stringArray[stringArray.length -1]) sb.append(" OR ");
}
//Now, you have a string like
//DELETE FROM YOURTABLE WHERE YOURFIELD='hello' OR YOURFIELD='YES'
//... do something with the command
This method will fail if you want to run SQL query on two (or multiple) columns using array values from two different arrays. .e.g
where col1=array1(i) and col2=array2(i)