木子屋 Dnawo's BLOG

[C#] Sql Server2000图片存取技术

👤 dnawo 📅 2009-09-15 👁 4526 👍 0 💬 0 🔄 来源:本站原创
//存储
private void button1_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=Northwind;User ID=sa;Password=sa"))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = conn;
            cmd.CommandText = "Insert INTO Images(Pic) Values(@Pic)";
            cmd.CommandType = CommandType.Text;

            //读取图片
            byte[] b;
            using (FileStream fs = new FileStream(@"F:\b1274.jpg", FileMode.Open))
            {
                b = new byte[fs.Length];
                fs.Read(b, 0, b.Length);
            }

            //添加参数
            SqlParameter[] parms = new SqlParameter[]{
                new SqlParameter("@Pic", SqlDbType.Image)
            };
            parms[0].Value = b;

            for (int i = 0; i < parms.Length; i++)
                cmd.Parameters.Add(parms[i]);

            cmd.ExecuteNonQuery();
        }
        conn.Close();
    }
}

//读取
private void button2_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=Northwind;User ID=sa;Password=sa"))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = conn;
            cmd.CommandText = "Select Top 1 Pic FROM Images orDER BY ID DESC";
            cmd.CommandType = CommandType.Text;

            pictureBox1.Image = Image.FromStream(new MemoryStream((byte[])cmd.ExecuteScalar()));
        }
        conn.Close();
    }
}

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 IE对CSS样式表的限制和解决方案 下一篇 → 使用MemoryStream与FileStream