Home>
private string sqlconnstr="data source=.;database=db_test;user id=sa;pwd=123456";
/* Function:Insert a picture 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 the SQL statement
  cmd.executenonquery ();
  conn.close ();
}
/* Function:read image files from the database,And displayed in the picturebox control
 * 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 bitstream of the first image
  memorystream mystream=new memorystream (data);
  //Create an image with the specified data stream
  system.drawing.image picbimage=system.drawing.image.fromstream (mystream, true);
  mystream.close ();
  picturebox1.image=picbimage;
  conn.close ();
}
c
  • Previous MySQL 5016 garbled solution
  • Next Example analysis of the use of Java's image buffering technology