【问题标题】:Error in inserting the image to Mysql将图片插入Mysql时出错
【发布时间】:2017-07-26 11:56:04
【问题描述】:

我正在使用 C# 将图像插入 Mysql 数据库。字节数组的长度是 51115。但是,当我在数据库中检查时,字段 IMage (Long Blob) 的长度只有 13 个字节。有什么问题?请帮帮我!

private void saveBtn_Click(object sender, EventArgs e)
{
    try
    {
        Image img = imgBox.Image;
        byte[] arr;
        ImageConverter converter = new ImageConverter();
        arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
        MessageBox.Show(arr.Length.ToString()); // 51115
        string connectionString = "server=localhost;user id=root;password=xrayadmin;database=xraydatabase";
        string query = "INSERT INTO imagedatabase(IDPatient,Image,DiagnosisDoctor,DiagnosisDate) VALUES('" + Convert.ToInt32(labPatID.Text) + "','" +
            arr + "','" + labDocUser.Text + "','" + DateTime.Now.ToString("dd / MM / yyyy") + "')";
        MySqlConnection MysqlConnection = new MySqlConnection(connectionString);
        MySqlCommand MysqlCmd = new MySqlCommand(query, MysqlConnection);
        MySqlDataReader DataReader;
        MysqlConnection.Open();
        DataReader = MysqlCmd.ExecuteReader();
        MessageBox.Show("Save Data");
        while (DataReader.Read())
        {

        }
        MysqlConnection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

}

【问题讨论】:

    标签: c# mysql image insert insert-image


    【解决方案1】:

    我建议您使用参数。像这样

    string query = @"INSERT INTO imagedatabase(IDPatient,Image,DiagnosisDoctor,DiagnosisDate) VALUES(@IDPatient,@Image,@DiagnosisDoctor,@DiagnosisDate)"
    MysqlCmd.Parameters.AddWithValue("@Image", arr);
    

    【讨论】:

      【解决方案2】:

      使用字符串连接时,数组将无法正确处理。

      您需要使用查询参数并将字节数组传递给参数。 .net 数据库函数将为您正确处理二进制数据。有关示例,请参阅Parameterized Query for MySQL with C#

      搜索堆栈溢出或您最喜欢的搜索引擎将针对您正在使用的任何数据类型生成正确参数类型的大量结果。

      顺便说一句,通过使用字符串连接来编写您的查询,您正在制造 SQL 注入的巨大风险(如果这是您的代码所指示的医疗数据,那么此类妥协的罚款美国和许多其他公司的数据非常昂贵)。这是一个非常非常坏的习惯,最好尽快改掉。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多