简体   繁体   中英

Deleting Multiple Rows from an Access Database

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.

string [] a = {"" 'a.jpg', 'b.jpg', 'c.jpg' "}

First, you have double " in the beginning,should only be one.

string [] a = {" 'a.jpg', 'b.jpg', 'c.jpg' "}

Then this created a string array with one element,

a[0] = "'a.jpg', 'b.jpg', 'c.jpg'";

Then you do a foreach on this which natuarly ony executes once resulting in this query:

delete from table1     where name not in ('a.jpg', 'b.jpg', 'c.jpg')

But when you load the array dynamically you probably get this array

a[0] = 'a.jpg';
a[1] = 'b.jpg';
a[1] = 'c.jpg';

which will execute 3 times in the foreach resulting in the following 3 queries

delete from table1     where name not in ('a.jpg')
delete from table1     where name not in ('b.jpg')
delete from table1     where name not in ('c.jpg')

After the second one the table will be empty.

You should try this instead:

string[] names = { "a.jpg", "b.jpg","c.jpg","j.jpg" };
string allNames = "'" + String.Join("','", names) + "'";

OleDbCommand sqlcmd = new OleDbCommand("delete from table1  where name not in (" + allNames + ")", sqlconnection); 
sqlcmd.ExecuteNonQuery(); 

Where names is created dynamically ofcause and this will result in the following query matching your test:

delete from table1     where name not in ('a.jpg', 'b.jpg', 'c.jpg')

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.

List<string> names = new List<string>();
//or user var keyword
var names = new List<string>();

Then just use add method to add elements, loop this as needed.

names.Add(filename);

Then for the concatenation:

string allNames = "'" + String.Join("','", names.ToArray()) + "'";

And you are done.

Or you could use

string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.jpg");
string[] names = filePaths.ToList().ConvertAll(n => n.Substring(n.LastIndexOf(@"\") + 1)).ToArray();

posting my comment as a answer

your string is not reading in 4 entries, its reading one entry of

string names = " 'a.jpg', 'b.jpg','c.jpg','j.jpg' ";

it should be

string[] names = { "a.jpg", "b.jpg","c.jpg","j.jpg" };

before your for each had a count of 1 now it should have a count of 4 with the actual values

Edit: Not a lot of effort in this solution i must admit but if you want dynamic input could do something like:

    string name = " 'a.jpg', 'b.jpg','c.jpg','j.jpg' ";
    string[] names = name.Split(',').Select(x => x.Trim(' ').Trim('\'')).ToArray();

will update later if i get the change as the trims are not good atm

For populating it, if you want it as enumerable a example could be something like

IEnumerable<string> filelocations = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x));

or for string array

string [] lok = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();

Sounds like you're either not reading the file correctly or the file is empty. You should be checking the array to make sure it's not empty before running the operation against the database. If the array is empty, it SHOULD delete everything in the database as there are no matches.

You need to define the array like this:

string[] names = { "a.jpg", "b.jpg", "c.jpg", "j.jpg" };

the way you are defining the array it contains only one value:

" 'a.jpg', 'b.jpg','c.jpg','j.jpg' "

The code in your comment will delete any files not matching the first file. that would be all non 'a.jpg' files. The next iteration will delete all files that don't match 'b.jpg' which would be 'a.jpg'. This results in an empty table. Edit: The array declaration you have generates a good IN clause when you do it manually, but when you're getting a list of filenames, you're not generating this same string.

You need to perform a join on the array to generate a single string for your where clause that way the where clause includes all files. Your ultimate where clause should look like:

where name not in ('a.jpg','b.jpg','c.jpg','d.jpg')

Right now you have:

where name not in ('a.jpg')

... next iteration

where name not in ('b.jpg')

Also, be mindful that IN operations are expensive and the longer the array is the faster the query grows.

Try using a list if you don't want to create a static sized array

List<string> names = new List<string>();
names.Add("a.jpg");
names.Add("b.jpg");
names.Add("c.jpg");


foreach (string name in names)
{
   OleDbCommand sqlcmd = new OleDbCommand("delete from table1 
   where name not in (" + name + ")", 
   sqlconnection); 
   sqlcmd.ExecuteNonQuery(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM