實(shí)例:如何用C#讀寫(xiě)數(shù)據(jù)庫(kù)Image字段
1、數(shù)據(jù)庫(kù)Image字段讀寫(xiě)文件
寫(xiě)文件:寫(xiě)文件的過(guò)程為將文件以流文件形式打開(kāi)并將內(nèi)容讀取到一個(gè)byte數(shù)組,然后將此byte數(shù)組寫(xiě)入數(shù)據(jù)庫(kù)的Image字段。
源碼:
FileInfo finfo=new FileInfo("文件名"); //絕對(duì)路徑
if(finfo.Exists)
{
SqlConnection conn=new SqlConnection("連接字符串");
SqlCommand InsertCommand=new SqlCommand();
InsertCommand.Connection=conn;
InsertCommand.CommandText="Insert into 表名(Image字段名) values(@Content)";
InsertCommand.Parameters.Add("@Content",SqlDbType.Image,(int)finfo.Length,"Image字段名"); //注意,此處參數(shù)Size為寫(xiě)入的字節(jié)數(shù)
//讀取文件內(nèi)容,寫(xiě)入byte數(shù)組
byte[] content=new byte[finfo.Length];
FileStream stream=finfo.OpenRead();
stream.Read(content,0,content.Length);
stream.Close();
InsertCommand.Parameters["@Content"].Value=content; //為參數(shù)賦值
try
{
conn.Open();
InsertCommand.ExcuteNonQuery();
}
finally
{
conn.Close();
}
}
讀文件:讀文件的過(guò)程為從數(shù)據(jù)庫(kù)的Image字段讀取內(nèi)容保存到byte數(shù)組,然后將此byte數(shù)組以文件流形式寫(xiě)入文件。
源碼:
byte[] content;
SqlConnetion conn=new SqlConnection("連接字符串");
SqlDataAdapter da=new SqlDataAdapter("Select Image字段名 from 表名",conn);
DataSet ds=new DataSet();
da.Fill(da,"word");
DataRow dr=ds.Tables["word"].Rows[0]; //將讀取的第一行內(nèi)容保存到dr
content=(byte[])dr["Image字段名"];
int ArraySize=content.GetUpperBound(0);
FileStream stream=new FileStream("文件名",FileMode.OpenOrCreate,FileAccess.Write);
stream.Write(content,0,ArraySize);
stream.Close();
2、數(shù)據(jù)庫(kù)Image字段讀寫(xiě)圖片
綁定到控件的方式:
通過(guò)將Image字段綁定到PictureBox實(shí)現(xiàn)。文件中我提供了一個(gè)實(shí)例,要正常運(yùn)行需要在Northwind中添加數(shù)據(jù)庫(kù)表Employees, 數(shù)據(jù)庫(kù)表的結(jié)構(gòu)為EmployeeID Int(4) 自動(dòng)增長(zhǎng),F(xiàn)irstName nvarchar(10),LastName nvarchar (20),Photo image(16) null。
直接用SqlCommand實(shí)現(xiàn):
其實(shí)把握住Image 字段存的是byte類(lèi)型數(shù)據(jù),用SqlCommand實(shí)現(xiàn)添加、修改就很簡(jiǎn)單了,跟文本的區(qū)別就是在讀出的時(shí)候需要將byte類(lèi)型數(shù)據(jù)轉(zhuǎn)化為Image圖 片,在寫(xiě)入時(shí)需要將Image圖片以流的形式轉(zhuǎn)為為byte數(shù)組,然后再將byte數(shù)組保存到Image字段。
實(shí)例:
comm = "Insert into MyEmployees(FirstName,LastName,Photo) values(@FName,@LName,@Photo)";
SqlCommand command=new SqlCommand(comm);
command.Connection = conn;
//創(chuàng)建Parameter
command.Parameters.Add("@FName",SqlDbType.NVarChar);
command.Parameters[0].Value = textBox1.Text;
command.Parameters.Add("@LName", SqlDbType.NVarChar);
command.Parameters[1].Value = textBox2.Text;
command.Parameters.Add("@Photo",SqlDbType.Image);
command.Parameters[2].Value = imgByte;
其中imgByte為Byte數(shù)組,通過(guò)FileStream的Read填充的byte數(shù)據(jù)。
實(shí)例:如何用C#讀寫(xiě)數(shù)據(jù)庫(kù)Image字段
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。