Method of accessing picture files in C operation database
- 2021-08-12 03:20:35
- OfStack
In this paper, an example is given to describe the method of accessing picture files in C # operation database. Share it for your reference. The details are as follows:
private string sqlconnstr = "Data Source=.;Database=db_test;User id=sa;PWD=123456";
/* Function: Put 1 Insert pictures into the database
* Return value: None
*/
void InsertImageToDB()
{
// Read the picture to be stored as a data stream
FileStream fs = new FileStream(@"D:/Bear.jpg", FileMode.Open, FileAccess.Read);
Byte[] byte_fs = new byte[fs.Length];
fs.Read(byte_fs, 0, Convert.ToInt32(fs.Length));
fs.Close();
// Establish a database connection
SqlConnection conn = new SqlConnection(sqlconnstr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into tb_test(image_id,image_file) values(@image_id,@image_file)";
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@image_id", SqlDbType.Int);
param[0].Value = 1;
param[1] = new sqlParameter("@image_file", SqlDbType.Image);
param[1].Value = byte_fs;
for (int index = 0; index < 2; index++)
{
cmd.Parameters.Add(param[i]);
}
// Execute SQL Statement
cmd.ExecuteNonQuery();
conn.Close();
}
/* Function: Read the image file from the database and display it in the PictureBox Control in the
* Return value: None
*/
void GetImageFromDB()
{
byte[] Data = new byte[0];
// Establish a database connection
SqlConnection conn = new SqlConnection(sqlconnstr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from tb_parent";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
Data = (byte[])sdr["parent_image"];// Read the 1 Bitstream of pictures
MemoryStream mystream = new MemoryStream(Data);
// Creates with the specified data flow 1 A image Picture
System.Drawing.Image picbImage = System.Drawing.Image.FromStream(mystream, true);
mystream.Close();
picturebox1.Image = picbImage;
conn.Close();
}
I hope this article is helpful to everyone's C # programming.