简体   繁体   English

从Access数据库中删除多行

[英]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. 问题是:以下是删除所有记录的代码,无论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: 然后,您对此进行一次foreach,实际上只有一次执行后才导致此查询:

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 这将在foreach中执行3次,导致以下3个查询

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. 然后,只需使用add方法添加元素,然后根据需要循环即可。

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 您的字符串没有读入4个条目,而是读了一个

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 在您的每个人的计数为1之前,现在应该有4的计数与实际值

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 如果我得到更改,稍后会更新,因为修剪不是很好的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. 那将是所有非“ a.jpg”文件。 The next iteration will delete all files that don't match 'b.jpg' which would be 'a.jpg'. 下一次迭代将删除所有与“ b.jpg”不匹配的文件,即“ 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. 编辑:当您手动执行数组声明时,会生成一个良好的IN子句,但是在获取文件名列表时,不会生成相同的字符串。

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. 您需要在数组上执行联接以为where子句生成单个字符串,从而使where子句包含所有文件。 Your ultimate where clause should look like: 您的最终where子句应如下所示:

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. 另外,请注意IN操作很昂贵,并且数组越长,查询增长越快。

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(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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