SqlParameter的作用与用法

public int SavePhoto(string photourl)
{
    FileStream fs = new FileStream(photourl, FileMode.Open, FileAccess.Read);//创建FileStream对象,用于向BinaryReader写入字节数据流
    BinaryReader br = new BinaryReader(fs);//创建BinaryReader对象,用于写入下面的byte数组
    byte[] photo = br.ReadBytes((int)fs.Length); //新建byte数组,写入br中的数据
    br.Close();//记得要关闭br
    fs.Close();//还有fs
    string sql = "update Table1 set photo = @photo where ID = '0'";
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=.\\SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|\\Database.mdf;User Instance=true";
    SqlCommand cmd = new SqlCommand(sql, conn);
    SqlParameter sp = new SqlParameter("@photo", photo);
    cmd.Parameters.Add(sp);
    try
    {
        conn.Open();
        return (cmd.ExecuteNonQuery());
    }
    catch (Exception)
    {
        return -1;
        throw;
    }
    finally
    {
        conn.Close();
    }
}
 
public void ReadPhoto(string url)
    {
        string sql = "select photo from Table1 where ID = '0'";
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = "Data Source=.\\SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|\\Database.mdf;User Instance=true";
        SqlCommand cmd = new SqlCommand(sql, conn);
        try
        {
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();//采用SqlDataReader的方法来读取数据
            if (reader.Read())
            {
                byte[] photo = reader[0] as byte[];//将第0列的数据写入byte数组
                FileStream fs = new FileStream(url,FileMode.CreateNew);创建FileStream对象,用于写入字节数据流
                fs.Write(photo,0,photo.Length);//将byte数组中的数据写入fs
                fs.Close();//关闭fs
            }
            reader.Close();//关闭reader
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
            conn.Close();
        }
    }
}

 

来自:http://www.cnblogs.com/pioneerlc/archive/2011/05/21/2053052.html

转载于:https://www.cnblogs.com/biye/articles/2567758.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值