2011-07-24 91 views
-1

我有一个问题,当我从内存流中的数据库检索图像时,它会给出错误Parameter is not valid。请帮我解决这个问题。从SQL Server数据库检索图像

代码:

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); 
} 
+2

错误在哪一行发生? – Tim

+0

什么**列表**你的表'testimg'包含?很可能,您在访问数据时只是拼错了列名。 –

回答

2

不知道你的问题的真正根源是 - 我的猜测是,有是在你的数据库表testimgimage名字没有列,但是你想阅读该栏目以获取您的照片。

但这里有几件事情我会建议为你的代码一般:

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); 
    } 
} 
+0

问题保持不变,列名和数据库名称正确。我应该为此做些什么。 – user721563

+0

@ user721563:你能告诉我们你的表结构吗?列名和数据类型 –

0

如果你的错误是关于将图像从数据库转换成流,只是试图修改这样的代码: :

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); 
+0

你为什么试图从封闭的流中访问对象?这是如何工作的? – Debaprasad

相关问题