我正在尝试在数据库Ms Access 2007中插入。首先,我从文件夹中获取所有文件名,然后将该文件名复制到数据库中。这是我的数据库截图。
这是我的代码
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();
我收到此错误
No value given for one or more required parameters.
第42行:int temp = cmd.ExecuteNonQuery();
答案 0 :(得分:3)
如果您使用过参数化查询,则永远不会看到此错误。问题出现在你的字符串连接中,为表中每个文本/备注字段中的值传递的字符串周围缺少引号。
参数化查询可能需要更多的输入,但更具可读性,并且可以避免在解析字符串,日期,小数等的值时出错...(以及称为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();