1.使用如下Python代码获取Oracle数据,只会查询出数据内容,不会带着字段名,怎么才能获取到带有字段名的数据?
import cx_Oracle
conn = cx_Oracle.connect('user/passwd@host/instance')
curs = conn.cursor()
sql = 'select * from tableA'
curs.execute(sql)
for result in curs:
print(result)
curs.close()
conn.close()
2.如何把从Oracle数据库提取的数据(上面代码中的 result )用pymysql转存到MySQL数据库中?分为两种,第一种是创建新表,另一种是替换已有表的数据全部内容
自己解决了,方法笨了点,但是实现了,具体代码如下:
import cx_Oracle as cx #连接Oracle 数据库的包
import pandas as pd
import pymysql #连接mysql数据库的包
from sqlalchemy import create_engine #执行SQL语句的包
engine = create_engine('mysql+pymysql://用户名:密码@IP:3306/db?charset=utf8') #连接mysql数据库
conn1 = pymysql.connect(host='IP',user='用户',passwd='密码',db='db',charset='utf8') #连接mysql数据库
cursor = conn1.cursor()
conn = cx.connect('用户','密码','IP:1521/db') # 链接Oracle数据库
cur = conn.cursor()
data = pd.read_sql('SELECT * FROM 表 WHERE 条件 ',conn,index_col='ID') #读取Oracle数据库的表,索引为ID
cursor.execute('drop table 表 ') #删除表,初次生成表不需要这一句
data.to_sql("表 ", con=engine) #把data写入MySQL数据库中
#关闭Oracle连接
cur.close() # 关闭游标
conn.close() # 关闭链接
#关闭MySQL连接
cursor.close()
conn1.close()