我正在尝试使用SQL INSERT INTO将刚刚上传的img源插入数据库。
这是我得到的行:
“在SQL语句结束时缺少分号(;)。”
错误。
command.CommandText = "INSERT INTO users (pic) VALUES (Images/"+fileName+") WHERE id="+theId;
这是整个.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();
}
}
}
}
答案 0 :(得分:7)
一些事情:
UPDATE
声明。如果您要转到INSERT
新记录,那么该陈述应该是:
command.CommandText = "INSERT INTO users (pic) VALUES (@image)";
command.Parameters.AddWithValue("@image", "Images / " + fileName);
如果您要更新,请使用:
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});
另请考虑在Connection
语句中附上Command
和using
对象,以确保正确处理资源。
注意到你实际上是在攻击MS Access。使用参数的概念应与SQL Server保持一致。有关使用OleDbcommand
添加参数的信息,请参阅此内容:using parameters inserting data into access database