Python与数据库(2)Oracle

用到的包:cx_Oracle

大致形式与Mysql类似,细节上有所不同

#-*-coding:GBK-*-
#author:zwg
import cx_Oracle as orc
#建立连接
dsn=orc.makedsn('127.0.0.1',1521,'ORCL')
conn=orc.connect('system','Python520',dsn)
#或者写成这种形式conn = cx_Oracle.connect('challenger/challenger@10.180.85.207/challenge')
#或者写成这种形式cx_Oracle.connect('username','pwd','IP/HOSTNAME:PORT/TNSNAME')
cursor=conn.cursor()
#cursor.execute('drop table student_copy')
sql1='create table student_copy(' \
     'a varchar(20),b varchar(20),c number(3),e varchar(10))'
sql2='select * from student_copy'
sql3='insert into system.student_copy ' \
     'select s_name,s_number,age,province from sys.student'
cursor.execute(sql1)
cursor.execute(sql3)

param1={'a':'LiSan','b':'16212044','c':26,'e':'HuNan'}
param2={'a':'LuSan','b':'16212014','c':25,'e':'HuNan'}
pa=[param1,param2]
cursor.executemany('insert into student_copy values(:a,:b,:c,:e)',pa);
#一次插入多条记录,为字典组成的列表数据,前面的mysql中是元组,且应用格式也有不同

cursor.execute(sql2)
text=cursor.fetchall()
length=len(text)
print(length)
conn.commit()
cursor.close()
conn.close()


(2)Oracle中数据写入MySQL,适用于数据量较少的情况,表较多时建议采用多线程模块同时进行

#-*-coding:GBK-*-
#author:zwg
import cx_Oracle as orc
import MySQLdb as msql
def connect_oracle(host,port,database,user,password):#建立与Oracle的连接
    dsn=orc.makedsn(host,port,database)
    conn=orc.connect(user,password,dsn)
    return conn
def connect_mysql(host,user,password,database):#建立与MySQL的连接
    conn=msql.connect(host,user,password,database)
    return conn
def write_txt(file1,text):#把数据写入txt
    a,b,c,d=text
    file1.writelines(str(a)+' '+str(b)+' '+str(c)+' '+str(d)+'\n')

conn1=connect_oracle('localhost',1521,'ORCL','system','Python520')
cursor1=conn1.cursor()
conn2=connect_mysql('127.0.0.1','root','1234','school')
cursor2=conn2.cursor()
sql1='select * from mysql_oracle'
sql2='insert into mysql_oracle values (%s,%s,%s,%s)'


cursor1.execute(sql1)
text1=cursor1.fetchall()
length1=len(text1)
length2=len(text1[0])
file1=file('mysql_oracle.txt','w+')
[write_txt(file1,text) for text in text1]
cursor2.executemany(sql2,text1)#直接将fetchall()得到的数据写入mysql
cursor2.execute(sql1)
conn2.commit()
conn1.commit()
text2=cursor2.fetchall()
print(len(text2))
cursor1.close()
conn1.close()
conn2.close()



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值