把圖片保存到數據庫的實現
導讀:可能在人們的意識中數據庫中存儲的全是一些數據之類的東西,其實數據庫的功能遠不止這些,圖片也是可以保存到數據庫中的,那么下文就為大家介紹實現將圖片保存到數據庫中的方法。
/// <summary>
/// 將照片轉換為二進制數組
/// </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 ;
}
//把二進制的圖片插到數據庫
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("把圖片成功的插入數據庫");
}
catch(Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
上文中主要是以代碼的形式展現出,可能不是很容易理解,大家還需要深入其中,并且還要有一定的數據庫知識作為基礎,希望文中介紹的內容能夠對大家有所幫助。
【編輯推薦】