简体   繁体   中英

Getting Error When Insert in Ms Access 2007 Using c#

I am trying to insert in database Ms Access 2007 . First i get all the file name from folder then copy that file name in database .Here is my Database screenshot.

这是我的数据库屏幕截图

This is my code

       string some = "Nothing";
        Response.Write(v);
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
        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();
        foreach (string item in filePaths)
        {
            a++;
            string filename = Path.GetFileName(item);
            string ips = 00 + a.ToString();



          cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES(" + filename + "," + ips + "," + some + "," +
           v + "," + some + "," + some + ");";


          int temp = cmd.ExecuteNonQuery();
          if (temp > 0)
          {
              Response.Write("Writing is complete, Success!");

          }
          else
          {
              Response.Write("Application Error, Try Again!");
          }


          Response.Write(filename+ "<br/>");

                  }
        mycon.Close();
        cmd.Dispose();
        mycon.Dispose();

I am Getting this error

       No value given for one or more required parameters.

In line Line 42: int temp = cmd.ExecuteNonQuery();

If you had used a parameterized query this error would never be seen. The problem is in your string concatenation that lacks of quotes around the string passed for the values in every text/memo field present in your table.

A parameterized query could require more typing but is more readable and will avoid error in parsing values for strings, dates, decimals etc.... (and that big problem called Sql Injection )

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",some);
cmd.Parameters.AddWithValue("@p4",v);
cmd.Parameters.AddWithValue("@p5",some);
cmd.Parameters.AddWithValue("@p6",some);
int temp = cmd.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