I want to delete multiple records from access database using array.
The array is loaded dynamically from file names.
Then i query the database, and see if the database column values are matching with the array values, if not then delete it, if matches then do not delete it.
the problem is that:
Following is the code that deletes all records irrespective of the where in Condition.
arrays = Directory.GetFiles(sdira, "*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
fnames.AddRange(arrays);
here I have use also for loop but that also didnt help me out :( like for(int u = 0; u < arrays.length; u++) { oledbcommand sqlcmd = new oledbcommand ("delete from table1 where name not in ("'+arrays[u]+"')",sqlconnection);
I am using this one currently foreach(string name in arrays)
{
OleDbCommand sqlcmd = new OleDbCommand("delete from table1 where name not in ('" + name + "')", sqlconnection);
sqlcmd.ExecuteNonQuery(); }`
One problem is that your code is confusing.
First, you have double ” in the beginning,should only be one.
Then this created a string array with one element,
Then you do a foreach on this which natuarly ony executes once resulting in this query:
But when you load the array dynamically you probably get this array
which will execute 3 times in the foreach resulting in the following 3 queries
After the second one the table will be empty.
You should try this instead:
Where names is created dynamically ofcause and this will result in the following query matching your test:
My preferred way to dynamically fill an array is to use a list instead as a pure array is fixed in size and any change needs to create a new array.
You can loop over a list as eacy as an array.
Then just use add method to add elements, loop this as needed.
Then for the concatenation:
And you are done.
Or you could use