工作中常遇到将图片保存到oracle的blob列中,这种是把图片以二进制数据流存入到oracle中,存入这个操作目前还没搞过,目前最多的是导出blob二进制数据流到图片,今天特地学习了下,尝试写了个python脚本,运行是OK的,顺便记录下,代码如下:
#!/usr/bin/python3 #coding:utf-8 __author__ = 'yang.su' import cx_Oracle import os server_ip = '127.0.0.1' server_port = '1521' oracle_user = 'c##merci' oracle_pass = 'admin123' oracle_sid = 'orcl' def oracle_connect(): _conn = False try: _dsn = cx_Oracle.makedsn(server_ip, server_port, oracle_sid) _conn = cx_Oracle.connect(oracle_user, oracle_pass, _dsn) except Exception as e: print('Conection False , %s' % e) _conn = False finally: return _conn def task_list(sql): try: conn = oracle_connect() cur = conn.cursor() result = cur.execute(sql) except Exception as e: print("Select failed , %s" % e) return result def save_image(task_list): for image_object in task_list: _object = image_object[10].read() try: filename = str(image_object[5]) + ".jpg" with open(filename, 'wb') as f: f.write(_object) print("Image , %s save successfly !" % filename) except Exception as e: print("Write image failed , %s" % e) if __name__ == '__main__': _list = task_list('select * from test where dbms_lob.getlength(photo) > 0') save_image(_list)
以上需要注意的地方是image_object[5]是图片名,循环遍历task_list或得到元祖image_object,第6个元素是名字,第11个元素是blob字段的值