用C#实现Oracle数据库BLOB字段与本地照片文件的存取操作


 (代码省略了对数据库连接的处理)
1、从数据库读取BLOB数据写入本地文件
   
    //  strid 主键字段名  strzp 照片字段名  strtb 数据库表名  strpath  存放照片的本地路径
    byte[] img = new byte[0];
    OracleCommand cmd = new OracleCommand();
    OracleDataReader rs;
    cmd.Connection = conn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select " + strid + ", " + strzp + " from " + strtb;
    rs = cmd.ExecuteReader();
    while (rs.Read())
    {
        img = (byte[])rs[1];
        System.IO.File.WriteAllBytes(strpath + "\\" + rs[0].ToString() + ".jpg", img);
    }
    rs.Close();
2、将本地图片文件存入数据库
    //参数说明:数据库表名,主键字段名,照片字段名,写入主键值,本地照片文件名,含完整路径
    private Boolean insertpic(string d_tb, string d_id, string d_zp, string id, string filename)
    {
        int result = 0;
        string strsql = "insert into " + d_tb + "(" + d_id + "," + d_zp + ") values('" + id + "', :pic)";
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = conn;
        cmd.CommandText = strsql;
           
        FileStream fs = System.IO.File.OpenRead(filename);
        byte[] imagebyte = new byte[fs.Length];
        fs.Read(imagebyte, 0, (int)fs.Length);
        cmd.Parameters.Add(new OracleParameter(":pic", imagebyte));
        try
        {
            result = cmd.ExecuteNonQuery();
        }
        catch
        {
            result = 0;
        }
        if (result == 1)
            return true;
        else
            return false;
    }

你可能感兴趣的:(用C#实现Oracle数据库BLOB字段与本地照片文件的存取操作)