#region Database image Access//<summary>//<strong><span style= "color: #ff0000;" > Import Pictures to Database </span></strong>//</summary>//<param name= "FilePath" ></param> ; public void Import (string filePath) {string fileName = filepath.substring (Filepath.lastindexof (@ "\") +1, Filepath.lastindexof (".") -filepath.lastindexof (@ "\")-1); FileStream FileStream = new FileStream (FilePath, FileMode.Open); byte[] imagebytes = new Byte[filestream.length]; BinaryReader BinaryReader = new BinaryReader (fileStream); Imagebytes = Binaryreader.readbytes (Convert.ToInt32 (filestream.length)); SqlConnection SqlConnection = new SqlConnection (@ "Data source=panlee-pc\mssqlserver_2;initial catalog=dbimage; Integrated security=true "); Sqlconnection.open (); SqlCommand sqlcommand=new SqlCommand (); Sqlcommand.connection = sqlConnection; Try {String sqlcreate = @ "Create Table Portraits (Study number varchar (50) , photo image,) "; Sqlcommand.commandtext = sqlcreate; SqlCommand.ExecuteNonQuery (); } catch {} sqlcommand.commandtext= "insert into portraits (school number, photo) VALUES (@ID, @Image)"; SQLCOMMAND.PARAMETERS.ADD ("Image", sqldbtype.image); SQLCOMMAND.PARAMETERS.ADD ("ID", SqlDbType.VarChar); sqlcommand.parameters["ID"]. Value = FileName; sqlcommand.parameters["Image"]. Value = imagebytes; SqlCommand.ExecuteNonQuery (); Sqlconnection.close (); }///<summary>//<strong>/<span style= "color: #ff0000;" > Export Pictures </span></strong>//</summary>//<param name= "SID" ></param> <returns>bitmap</returnS> Public Bitmap Export (string SID) {byte[] imagebytes = null; SqlConnection SqlConnection = new SqlConnection (@ "Data source=panlee-pc\mssqlserver_2;initial catalog=dbimage; Integrated security=true "); Sqlconnection.open (); SqlCommand SqlCommand = new SqlCommand ("Select photo from portraits where study number [email protected]", sqlConnection); SQLCOMMAND.PARAMETERS.ADD ("ID", SqlDbType.VarChar); sqlcommand.parameters["ID"]. Value = SID; SqlDataReader SqlDataReader = SqlCommand.ExecuteReader (); while (Sqldatareader.read ()) {imagebytes = (byte[]) sqldatareader.getvalue (0); } sqldatareader.close (); Sqlcommand.clone (); Sqlconnection.close (); MemoryStream ms = new MemoryStream (imagebytes); Bitmap Bitmap = new Bitmap (MS); return bitmap; } #endregion
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C # SQL Server database picture access