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

//存储
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 | 引用: 0 | 查看次数: 3813
发表评论
登录后再发表评论!