把圖片保存到數(shù)據(jù)庫的實(shí)現(xiàn)
導(dǎo)讀:可能在人們的意識(shí)中數(shù)據(jù)庫中存儲(chǔ)的全是一些數(shù)據(jù)之類的東西,其實(shí)數(shù)據(jù)庫的功能遠(yuǎn)不止這些,圖片也是可以保存到數(shù)據(jù)庫中的,那么下文就為大家介紹實(shí)現(xiàn)將圖片保存到數(shù)據(jù)庫中的方法。
/// <summary>
/// 將照片轉(zhuǎn)換為二進(jìn)制數(shù)組
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private byte[] PhotoToArray( string path )
{
FileStream stream = new FileStream( path , FileMode.Open , FileAccess.Read ) ;
byte[] bufferPhoto =new byte[stream.Length] ;
stream.Read( bufferPhoto,0,Convert.ToInt32( stream.Length ) ) ;
stream.Flush();
stream.Close();
return bufferPhoto ;
}
//把二進(jìn)制的圖片插到數(shù)據(jù)庫
private void Save(byte[] image)
{
string sql = "insert into table2(aaa,photo) values(@aaa,@photo)";
SqlParameter[] param=new SqlParameter[2];
param[0] =new SqlParameter("@aaa",SqlDbType.Int);
param[0].Value = 1;
param[1]= new SqlParameter("@photo",SqlDbType.Image);
param[1].Value= image;
SqlConnection conn= new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings[0];
SqlCommand commd= new SqlCommand(sql,conn);
commd.Parameters.Add(param[0]);
commd.Parameters.Add(param[1]);
try
{
conn.Open();
commd.ExecuteNonQuery();
MessageBox.Show("把圖片成功的插入數(shù)據(jù)庫");
}
catch(Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
上文中主要是以代碼的形式展現(xiàn)出,可能不是很容易理解,大家還需要深入其中,并且還要有一定的數(shù)據(jù)庫知識(shí)作為基礎(chǔ),希望文中介紹的內(nèi)容能夠?qū)Υ蠹矣兴鶐椭?br />
【編輯推薦】