Eta*_*sky 0 c# sql asp.net ms-access
我正在尝试使用SQL INSERT INTO将刚刚上传的img源插入数据库.
这是我得到的线:
"在SQL语句结束时缺少分号(;)."
错误.
command.CommandText = "INSERT INTO users (pic) VALUES (Images/"+fileName+") WHERE id="+theId;
Run Code Online (Sandbox Code Playgroud)
这是整个.aspx.cs文件:
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Collections.Generic;
public partial class CS : System.Web.UI.Page
{
protected void Upload(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
string theId = Request.Cookies["Logged"].Value;
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (pic) VALUES (Images/"+fileName+") WHERE id="+theId;
int rows = command.ExecuteNonQuery();
Response.Redirect("~/signIn.cshtml");
}
finally
{
connection.Close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
几件事:
UPDATE如果您尝试修改现有记录,则可能需要
声明.如果你要去INSERT新记录那么声明应该是这样的:
command.CommandText = "INSERT INTO users (pic) VALUES (@image)";
command.Parameters.AddWithValue("@image", "Images / " + fileName);
Run Code Online (Sandbox Code Playgroud)
如果您要更新,请使用:
command.CommandText = "UPDATE users SET PIC = @images WHERE id=@id";
command.Parameters.AddWithValue("@image", "Images / " + fileName);
command.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) {Value = theId});
Run Code Online (Sandbox Code Playgroud)
还要考虑封闭Connection和声明中的Command对象using,以确保正确处理资源.
刚刚注意到你实际上是在攻击MS Access.使用参数的概念应与SQL Server保持一致.请参阅以下内容以添加参数OleDbcommand:使用将数据插入访问数据库的参数