[英]Retrieve images from SQL Server database
我有一個問題,當我從內存流中從數據庫檢索圖像時,它給出了一個錯誤Parameter is not valid
。 請幫我解決這個問題。
碼:
private void button3_Click(object sender, EventArgs e)
{
string strcon = "Data Source=PINKAL-PC; initial catalog=testing; integrated security=SSPI;";
SqlConnection sqlcon = new SqlConnection(strcon);
sqlcon.Open();
string strquery = "select * from testimg";
SqlDataAdapter da = new SqlDataAdapter(strquery,sqlcon);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
byte[] barrImg = (byte[])dt.Rows[7]["image"];
MemoryStream mstream = new MemoryStream(barrImg);
pictureBox2.Image = Image.FromStream(mstream);
}
不知道問題的真正根本原因是什么-我的猜測是數據庫表testimg
沒有image
名稱的列,但是您正在嘗試讀取該列以獲取圖片。
但是,總體上,我建議您為您的代碼提供一些建議:
private void button3_Click(object sender, EventArgs e)
{
string strcon = "Data Source=PINKAL-PC; initial catalog=testing; integrated security=SSPI;";
// Put your SqlConnection into using blocks to ensure proper disposal
using(SqlConnection sqlcon = new SqlConnection(strcon))
{
// sqlcon.Open(); -- don't open it here already - open as LATE as possible....
// for SqlDataAdapter - you don't even need to open it yourself -
// the data adapter will do this automatically for you
// and **IF** you open it yourself - you also need to CLOSE it again!
// *NEVER* use SELECT * in code !! specify the columns you want explicitly
// string strquery = "select * from testimg";
string strquery = "SELECT col1, col2, col3 ..... FROM dbo.testimg";
SqlDataAdapter da = new SqlDataAdapter(strquery, sqlcon);
//DataSet ds = new DataSet(); if you only want a single DataTable - no point in having a whole DataSet ! That's just overhead.....
//da.Fill(ds);
//DataTable dt = new DataTable();
//dt = ds.Tables[0];
DataTable dt = new DataTable();
da.Fill(dt);
// is there a "image" column in your table??
// You need to use the proper column name here!
byte[] barrImg = (byte[])dt.Rows[7]["image"];
MemoryStream mstream = new MemoryStream(barrImg);
pictureBox2.Image = Image.FromStream(mstream);
}
}
如果您的錯誤與將圖像從數據庫轉換為流有關,則只需嘗試修改代碼即可:
byte[] barrImg = (byte[])dt.Rows[7]["image"];
MemoryStream mstream = new MemoryStream();
mstream .Write ( barrImg, 0, barrImg.Length );
mstream .Seek ( 0, SeekOrigin.Begin );
mstream .Close();
pictureBox2.Image = Image.FromStream(mstream);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.