1

我使用 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());
    }

}
4

2 回答 2

2

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

string query = @"INSERT INTO imagedatabase(IDPatient,Image,DiagnosisDoctor,DiagnosisDate) VALUES(@IDPatient,@Image,@DiagnosisDoctor,@DiagnosisDate)"
MysqlCmd.Parameters.AddWithValue("@Image", arr);
于 2017-07-26T03:20:21.490 回答
2

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

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

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

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

于 2017-07-26T03:22:20.270 回答