c# - 无法将参数值从 Byte[] 转换为 String

标签 c# mysql asp.net string byte

我正在使用 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/

相关文章:

c# - 如何检查重复键并从字典中删除以前的值?

c# - 如何使用 OnPaint args 在 C# 中向 TreeView 控件添加图标

MYSQL 左连接在索引列上速度极慢

.net - 在 asp.net 3.5 中将 List<string> 绑定(bind)到 Listview

带有 Javascript 的 ASP.NET Web 用户控件在页面上多次使用 - 如何使 javascript 函数指向正确的控件

c# - 使用 IEnumerable<T> 作为委托(delegate)返回类型

c# - ReSharper 忽略 TODO 资源管理器上的某些文件夹

sql - SQL Server 使用什么来代替 "Key"?

MYSQL 在每次调用时切换枚举值

asp.net - 将外部 .config 文件合并回使用 configSource 提取的 web.config