Foreach循环无法正常工作

时间:2013-07-28 21:34:31

标签: c# asp.net foreach ms-access-2007

当我使用参数化查询循环在string filename = Path.GetFileName(item);变量中一次又一次地获取一个文件名时,此代码中存在问题

 string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + newtable));


    int a = 0;

    OleDbCommand cmd = new OleDbCommand();

    OleDbConnection mycon = new OleDbConnection();

    mycon.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb";

    cmd = mycon.CreateCommand();

    mycon.Open();

    DateTime dateTime = DateTime.UtcNow.Date;
    foreach (string item in filePaths)
    {
        a++;
        string filename = Path.GetFileName(item);
        string ips = "00" + a.ToString();

       // Response.Write("Number (" + a.ToString() + ")    " + filename + "    " + ips + "    " + t1 + "     " + v + "     " + some + "   " + some + "<br/><br/>");

       // cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
        cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
        cmd.Parameters.AddWithValue("@p1", filename);
        cmd.Parameters.AddWithValue("@p2", ips);
        cmd.Parameters.AddWithValue("@p3", dateTime.ToString("dd/MM/yyyy"));
        cmd.Parameters.AddWithValue("@p4", newtable);
        cmd.Parameters.AddWithValue("@p5", TextBox4.Text);
        cmd.Parameters.AddWithValue("@p6", TextBox3.Text);
        cmd.ExecuteNonQuery();
    }

但是当我使用普通插入查询时

     cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";

循环工作正常,并获取特定位置的所有文件名。请告诉我原因?我的逻辑有什么问题吗?

1 个答案:

答案 0 :(得分:2)

迭代之间不会清除

cmd.Parameters集合。您应该在循环之前创建参数并在循环中设置值,而不是使用AddWithValue

cmd = mycon.CreateCommand();
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.Add('@p1',...);
...same for other params...

mycon.Open();

DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
    a++;
    string filename = Path.GetFileName(item);
    string ips = "00" + a.ToString();       

    cmd.Parameters["@p1"].Value = filename;
    ...same for other params...

    cmd.ExecuteNonQuery();
}

但是,您只需在cmd.Parameters.Clear()之后添加cmd.ExecuteNonQuery():)

正如MSDN中所述

  

OleDbParameterCollection.AddWithValue方法

     

在OleDbParameterCollection

的末尾添加一个值

所以引擎在第二次迭代时没有看到@ p1,因为它已经在第一次迭代中添加了@ p1。