c# - 如何使用C#在MYSQL中插入和检索图像

标签 c# mysql phpmyadmin xampp

有没有办法使用 phpMyAdmin 和 XAMPP 在 MySQL 数据库中插入和检索图像(图片本身)?我正在使用 C#。

private void button1_Click(object sender, EventArgs e)
{
    //this button will save my pic from the picturebox to the database
    String strAddress = " Data Source = 127.0.0.1; Initial Catalog= ex; user id = root; password= ''";
    MySqlConnection sqlConn = new MySqlConnection(strAddress);
    MySqlCommand sqlcomm = new MySqlCommand();

    sqlConn.Open();
    sqlcomm.CommandText = "INSERT INTO ta VALUES(" + pictureBox1.Image  + "')";
    sqlcomm.CommandType = CommandType.Text;
    sqlcomm.Connection = sqlConn;
    sqlcomm.ExecuteNonQuery();
    sqlConn.Close();
    MessageBox.Show("RECORD SAVED!", "SAVING", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private void button2_Click(object sender, EventArgs e)
{
    //this will put an image in the picturebox 
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Open Image";
    //dlg.Filter = "bmp files (*.bmp)|*.bmp";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
    }
    dlg.Dispose();
}

最佳答案

我认为将图像存储在数据库中不是一个好主意。但是,如果这是您的要求,那么您可以做类似的事情

using (MySqlConnection conn = new MySqlConnection("Your Connection String"))
{
 string myQuery = "SELECT IMAGE FROM SOMETABLE";

    using(MySqlCommand cmd = new MySqlCommand(myQuery, conn))
    {
       conn.Open();
       using(var reader = new cmd.ExecuteReader())
       {
         someVariable = (byte[])reader["IMAGE"];
       }
    }
}

这是假设您的数据库中有一列数据类型为 BLOB。您还需要安装 Install-Package MySql.Data

关于c# - 如何使用C#在MYSQL中插入和检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29009977/

相关文章:

c# - 使用列表从 MySql 数据库检索信息出现异常 "Index was outside the bounds of the array."

c# - 是否可以从 .NET 测试暴露于 COM 的程序集?

mysql - 是否可以复制一个架构并创建新的架构

java - 无法从 Java Spring 应用程序连接到 MySQL,即使它可以从控制台运行

mysql - 堆叠式 SQL 查询错误和并发症

php - 使用 phpMyAdmin 的跟踪机制迁移数据库

c# - MVC3 - 发布时模型为空

c# - 从 Div 标签中提取内容 C# RegEx

c# - C# 泛型集合中的倒排索引

Java、MySQL : I save "Česká Třebová", 但保存了 "?eská T?ebová"(来自终端一切正常)