Q: save images to the database
A: using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. Data. sqlclient;
Using system. IO;
Namespace cexample
{
Public class imagedb: system. Windows. Forms. Form
{
Private system. Windows. Forms. Button btnadd;
Private system. Windows. Forms. Label label1;
Private system. Windows. Forms. textbox edtid;
Private system. Windows. Forms. textbox edtimage;
Private system. Windows. Forms. Label label2;
Private system. Windows. Forms. Button btnshow;
Private system. Windows. Forms. picturebox studentphoto;
...
Private void btnadd_click (Object sender, system. eventargs E)
{
Addstudentphoto (102, @ "C: \ temp \ 1.jpg ");
}
Private void addstudentphoto (INT student_id, string imagefile)
{
Filestream myfile = new filestream (imagefile, filemode. Open, fileaccess. Read );
Byte [] photo = new byte [myfile. Length];
Myfile. Read (photo, 0, (INT) myfile. Length );
Myfile. Close ();
Savephotodb (student_id, photo );
}
Private void savephototodb (INT student_id, byte [] photo)
{
String connectstring = "Data Source = hellcat; initial catalog = SMS;" +
"User ID = ***; Password = ***";
Using (sqlconnection mycon = new sqlconnection (connectstring ))
{
If (mycon. State! = Connectionstate. Open) // If connection is not open, open it
Mycon. open ();
Sqlcommand mycmd = new sqlcommand ("addstudentphoto", mycon );
Mycmd. commandtype = commandtype. storedprocedure;
Mycmd. Parameters. Add (New sqlparameter ("@ student_id", sqldbtype. Int, 0 ));
Mycmd. Parameters. Add (New sqlparameter ("@ photo", sqldbtype. Image ));
Mycmd. Parameters ["@ student_id"]. value = student_id;
Mycmd. Parameters ["@ photo"]. value = photo;
Mycmd. executenonquery ();
Mycon. Close ();
MessageBox. Show ("add student photo successfully! ");
}
}
}
}