#工具库导入import pandas as pdimport cx_Oracle# 注:设置环境编码方式,可解决读取数据库乱码问题import osos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'#实现查询并返回dataframedef 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 resultstest_data = query(test_table) # 可以得到结果集
#工具库导入import pandas as pdimport 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)
#!/usr/bin/python#coding=utf-8import threadingimport osimport time#用户名user = 'username'#密码passwd = 'password'#备份保存路径savepath = '/home/oracle/orcl_bak/'#要备份的表tables = ' tables=department,employee'#备份周期circle = 2.0#备份命令global bak_commandbak_command = 'exp '+user+'/'+passwd + ' file=' + savepathdef 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()