Reputation: 11
Is there a way to insert and retrieve images (the pic itself) in a MySQL Database using phpMyAdmin and XAMPP? I'm using 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();
}
Upvotes: 1
Views: 4189
Reputation: 6866
I don't think its a very good idea to be storing images in the Database. However if that is your requirement then you can do something like
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"];
}
}
}
This is assuming you have a column in your DB of datatype BLOB
. Also you will need to install Install-Package MySql.Data
package
Upvotes: 1
Reputation: 129
You can store the actual images in the Database but it really isn't advisable.
Store images in directories and within your database store references to the images(eg the path to the image).
Images can be quite large and take up an unnecessary amount of space in your database.
Upvotes: 0