Save images to the database

Source: Internet
Author: User

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! ");
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.