将图像存储到数据库中但面临异常

时间:2015-03-12 06:19:32

标签: c# asp.net

我正在尝试将图像插入到数据库中,但是当尝试保存图像时会发生异常“使用'附近的语法不正确'。”请指导。

我的代码是:

 protected void Button1_Click(object sender, EventArgs e)
   {
       string InsertImage = "insert into Record(Name,Picture) using (@name,@img)";
       SqlCommand cmd = new SqlCommand(InsertImage, MySQL);
       cmd.Parameters.AddWithValue("@name", TextBox2.Text);
       int dataSize= FileUpload1.PostedFile.ContentLength;
       byte[] ImgByte = new byte[dataSize];
       FileUpload1.PostedFile.InputStream.Read(ImgByte, 0, dataSize);
       cmd.Parameters.AddWithValue("@img", ImgByte);
       if (MySQL.State == ConnectionState.Closed)
       {
           MySQL.Open();
       }
       cmd.ExecuteNonQuery();
       MySQL.Close();
       Response.Write("Image has been stored");
   }

4 个答案:

答案 0 :(得分:1)

尝试使用此声明

string InsertImage = "insert into Record(Name,Picture) values (@name,@img)";

答案 1 :(得分:1)

绝对是您的语法不正确。在插入上没有使用,而对于MySQL使用标记而不是 @ 尝试这个:

string InsertImage = "insert into Record(Name,Picture) values(?name,?img)";
...
cmd.Parameters.AddWithValue("?name", TextBox2.Text);
...

http://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html

上有完整的示例

答案 2 :(得分:1)

您的插入语句错误。请尝试以下声明:

string InsertImage = "insert into Record (Name,Picture) values (@name,@img)";

答案 3 :(得分:1)

你为什么要尝试insert into Record(Name,Picture) using (@name,@img)

尝试这个简单的插入查询insert into Record(Name,Picture) values(@name,@img)