[英]Retrieve Images from sql server database Error
我將圖像存儲到名為test contains(id,name,image)的表上的數據庫中,但是當我嘗試通過使用以下代碼來檢索圖像時:
SqlConnection CN = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("select * from test where id ='"+txtid.Text+"'", CN);
SqlDataReader myreader;
try
{
CN.Open();
myreader = cmd.ExecuteReader();
if (myreader.HasRows)
{
txtid.Text = myreader[0].ToString();
txtname.Text = myreader[1].ToString();
byte[] img = (byte[])(myreader[2]);
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("do not found");
}
CN.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
我有此錯誤: invalid attempt to read when no data is present
。
HasRows
只是確定是否有行。 您還需要Read()
才能使讀者前進。
這樣的事情應該起作用(假設您只想要一行)。
myreader = cmd.ExecuteReader();
if (myreader.Read())
{
...
還請確保參數化您的SQL選擇-目前它很容易受到SQL注入攻擊,並Dispose
諸如MemoryStream
和DataReader
類的東西
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.