我正在使用 c# asp.net 构建一个应用程序。我需要将一些数据插入数据库。一切正常,但我在插入图像时遇到问题。
我的数据库表:
顺序
OrderID int
description varchar(50)
numOfItems int
material varchar(50)
image varbinary(max)
我的将数据插入数据库的代码
protected void btnAddItem_Click(object sender, EventArgs e)
{
string filepath = fileUpload.PostedFile.FileName;
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
string contentType = String.Empty;
switch (ext)
{
case ".jpg":
contentType = "image/jpg";
break;
case ".png":
contentType = "image/png";
break;
case ".gif":
contentType = "image/gif";
break;
case ".pdf":
contentType = "application/pdf";
break;
}
if (contentType != String.Empty)
{
Stream fs = fileUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string kon = ConfigurationManager.ConnectionStrings["mk"].ConnectionString;
using (SqlConnection conn = new SqlConnection(kon))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Order(description, numOfItems, material, image"))
{
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@description", inputTextArea.Text);
cmd.Parameters.AddWithValue("@numOfItems", inputTextArea.Text);
cmd.Parameters.AddWithValue("@material", inputTextArea.Text);
cmd.Parameters.Add("@image", SqlDbType.VarChar).Value = bytes;
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("Success!");
}
}
}
}
当我这样做时,出现以下错误:无法将参数值从 Byte[] 转换为字符串。
有什么想法吗?
更新 - 新错误
“图像”附近的语法不正确。错误。有什么想法吗?
最佳答案
对于参数 @image
,传递的值是一个字节数组,但您指定输入将是 VarChar
,将其更改为 Binary
.所以添加特定参数的语句将如下所示
cmd.Parameters.Add("@image", SqlDbType.Binary).Value = bytes;
并且您必须将占位符添加到您的查询中,这意味着查询文本应该是这样的:
"INSERT INTO Order(description, numOfItems, material, image)values(@description, @numOfItems,@material,@image)"
关于c# - 无法将参数值从 Byte[] 转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882591/