Reputation: 782
I want to insert an image to my database using a FileUpload control. I have tried to do this with the following code:
protected void btnUploadAvatar_Click(object sender, EventArgs e)
{
if (fuAvatar.PostedFile != null && fuAvatar.PostedFile.FileName != "") ;
{
byte[] imageSize = new byte[fuAvatar.PostedFile.ContentLength];
HttpPostedFile uploadImage = fuAvatar.PostedFile;
uploadImage.InputStream.Read(imageSize, 0, fuAvatar.PostedFile.ContentLength);
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO User(image" + "VALUES (@Image) WHERE userid = @Userid";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
SqlParameter userid = new SqlParameter("@Userid", SqlDbType.Int);
userid.Value = Convert.ToInt32(Session["userid"]);
cmd.Parameters.Add(userid);
cmd.Parameters.Add(UploadedImage);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
/*if(result > 0)
{
lblResult.Text = "Avatar lastet opp";
}*/
}
}
But i get a error on cmd.ExecuteNonQuery(); which says: SqlException unhandled by user code, Incorrect syntax near the keyword 'User'. I have tried both *.jpg and *.png files of under 10KB size.
Upvotes: 0
Views: 4990
Reputation: 499382
You have a syntax error:
cmd.CommandText =
"INSERT INTO User(image" + "VALUES (@Image) WHERE userid = @Userid";
There is a missing )
and spacing there:
cmd.CommandText =
"INSERT INTO User(image)" + " VALUES (@Image) WHERE userid = @Userid";
Or, better yet (why concatenate at all?):
cmd.CommandText =
"INSERT INTO User(image) VALUES (@Image) WHERE userid = @Userid";
Upvotes: 1