資料庫圖檔的存取
使用的工具:sqlserver2012、VS2010
方法:二進制資料将圖檔儲存到資料庫,并讀取資料庫二進制資料顯示圖檔
①将圖檔儲存至資料庫
資料庫表中新增一列‘img’用于存放圖檔的二進制資料
//例如在food表中增加food_id=10001的一行,img列對應圖檔的二進制資料
insert into dbo.food(food_id,img) select '10001', BulkColumn from openrowset(bulk N'E:\作業\期末作業\image\10001.png', single_blob) as blob
//或者
update dbo.food set img=BulkColumn from openrowset(bulk N'E:\作業\期末作業\image\10001.png', single_blob) as blob where food_id=10001
②讀取資料庫二進制資料顯示圖檔
首先可以先建立一個單獨的Web窗體:pic.aspx
public partial class pic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//網站内置對象Session:用于傳值,判斷是否為空(此步必須有)
if (Session["food_id"] != null)
{
//擷取food_id的值
string x = Session["food_id"].ToString();
int fid = Convert.ToInt32(x);
if (fid!=0)
{
//資料庫連接配接
string connString = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
//查詢對應的圖檔二進制資料
string sqlString = "SELECT img FROM Food WHERE food_id='" + fid + "'";
cmd.CommandText = sqlString;
conn.Open();
SqlCommand sqlcommand = new SqlCommand(sqlString, conn);
SqlDataReader reader = cmd.ExecuteReader();
//圖檔二進制資料的讀取轉換和顯示
if (reader.Read())
{
Response.ContentType = "image/png";
Response.BinaryWrite((Byte[])reader["img"]);
}
Response.End();
conn.Close();
Session["food_id"] = null;
}
}
}
}
注:此方法友善存取,但會增加資料庫的負擔。