Python读写及备份oracle数据库 Python读写及备份oracle数据库操作示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python读写及备份oracle数据库 Python读写及备份oracle数据库操作示例

不一样吗   2021-03-31 我要评论

本文实例讲述了Python读写及备份oracle数据库操作。分享给大家供大家参考,具体如下:

最近项目中需要用到Python调用oracle实现读写操作,踩过很多坑,历尽艰辛终于实现了。性能怎样先不说,有方法后面再调优嘛。现在把代码和注意点记录一下。

1. 所需Python工具库

cx_Oraclepandas,可以使用通过控制台使用pip进行安装(电脑中已经安装)

2. 实现查询操作

#工具库导入
import pandas as pd
import cx_Oracle
# 注:设置环境编码方式,可解决读取数据库乱码问题
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
#实现查询并返回dataframe
def query(table)
  host = "127.0.0.1"  #数据库ip
  port = "1521"   #端口
  sid = "test"  #数据库名称
  dsn = cx_Oracle.makedsn(host, port, sid)
  #scott是数据用户名,tiger是登录密码(默认用户名和密码)
  conn = cx_Oracle.connect("scott", "tiger", dsn)
  #SQL语句,可以定制,实现灵活查询
  sql = 'select * from '+ table
  # 使用pandas 的read_sql函数,可以直接将数据存放在dataframe中
  results = pd.read_sql(sql,conn)
  conn.close
  return results
test_data = query(test_table) # 可以得到结果集

3. 实现插入操作

#工具库导入
import pandas as pd
import cx_Oracle
#实现插入功能
def input_to_db(data,table):
  host = "127.0.0.1"  #数据库ip
  port = "1521"   #端口
  sid = "test"  #数据库名称
  dsn = cx_Oracle.makedsn(host, port, sid)
  #scott是数据用户名,tiger是登录密码(默认用户名和密码)
  conn = cx_Oracle.connect("scott", "tiger", dsn)
  #建立游标
  cursor = connection.cursor()
  #sql语句,注意%s要加引号,否则会报ora-01036错误
  query = "INSERT INTO"+table+"(name,gender,age) VALUES ('%s', '%s', '%s')"
  #逐行插入数据
  for i in range(len(data)):
    name= data.ix[i,0]
    gender= data.ix[i,1]
    age= data.ix[i,2]
   # 执行sql语句
    cursor.execute(query % (name,gender,age))
  connection.commit()
  # 关闭游标
  cursor.close()
  connection.close()
#测试插入数据库
#测试数据集
test_data = pd.DataFrame([['小明','男',18],['小芳','女',18]],index = [1,2],columns=['name','gender','age'])
#调用函数实现插入
input_to_db(test_data,test_table1)

4. Python备份Oracle数据库

#!/usr/bin/python
#coding=utf-8
import threading
import os
import time
#用户名
user = 'username'
#密码
passwd = 'password'
#备份保存路径
savepath = '/home/oracle/orcl_bak/'
#要备份的表
tables = ' tables=department,employee'
#备份周期
circle = 2.0
#备份命令
global bak_command
bak_command = 'exp '+user+'/'+passwd + ' file=' + savepath
def orclBak():
  now = time.strftime('%Y-%m-%d %H:%M:%S')
  command = bak_command + now + '.dmp' + tables
  print command
  if os.system(command) == 0:
    print '备份成功'
  else:
    print '备份失败'
  global t
  t = threading.Timer(circle, orclBak)
  t.start()
t = threading.Timer(circle, orclBak)
t.start()

希望本文所述对大家Python程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们