:
Download link
1. Create a WinForm form, the form is divided into "data upload" and "data read" two parts;
2. In the SQL Server database, create a data table named Peopleinformation with three fields in the table: ID, Name, Photo.
3. Set the ID field as the primary key, and the self-increment
Image upload Code
1 //read local picture information via data stream2FileStream fs =NewFileStream (Path, FileMode.Open, FileAccess.Read);3 byte[] bt =New byte[FS. Length];4Fs. Read (BT,0, Bt. Length);5 FS. Close ();6 //Open a connection to a database7 stringstrconn =@"Data source=long-pc\;initial Catalog=practice; User id=istrive; Password=istrive";8SqlConnection conn =NewSqlConnection (strconn);9 Conn. Open ();Ten //uploading information to SQL Server One stringStrcmd ="INSERT INTO peopleinformation (Name,photo) VALUES (@name, @photo)"; ASqlCommand cmd =NewSqlCommand (); -Cmd. Connection =Conn; -Cmd.commandtext =Strcmd; theCmd. Parameters.Add (NewSqlParameter ("@name", Txtupload.text)); -Cmd. Parameters.Add (NewSqlParameter ("@photo", BT)); - cmd. ExecuteNonQuery (); - //To close a database connection +Conn. Close ();
The code that the picture reads:
1 //Open a database connection2 stringStrcoon =@"Data source=long-pc\;initial Catalog=practice; User id=istrive; password=istrive; Connect timeout=5";3SqlConnection conn =NewSqlConnection (strcoon);4 Conn. Open ();5 //Querying the database6 stringStrcmd ="Select Name,photo from peopleinformation where Name = @name";7SqlCommand cmd =NewSqlCommand (STRCMD, conn);8Cmd. Parameters.Add (NewSqlParameter ("@name", name));9SqlDataAdapter adap =NewSqlDataAdapter (cmd);TenDataTable dt =NewDataTable (); One cmd. ExecuteNonQuery (); A ADAP. Fill (DT); - //reads picture information from a DataTable as a data stream - if(dt. Rows.Count! =0) the { -MemoryStream ms =NewMemoryStream ((byte[]) dt. rows[0]["Photo"]); -Picread.image = Image.fromstream (MS,true); -}
C # Read and write SQL Server database pictures