使用Python怎么对甲骨文数据库进行读写操作

  介绍

使用Python怎么对甲骨文数据库进行读写操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

<强> 1。所需Python工具库

cx_Oracle,熊猫,可以使用通过控制台使用<代码> pip 进行安装(电脑中已经安装)

使用Python怎么对甲骨文数据库进行读写操作

<强> 2。实现查询操作

#工具库导入   import  pandas  as  pd   import  cx_Oracle   #,注:设置环境编码方式,可解决读取数据库乱码问题   import 操作系统   os.environ [& # 39; NLS_LANG& # 39;],=, & # 39; SIMPLIFIED  CHINESE_CHINA.UTF8& # 39;   #实现查询并返回dataframe   def 查询(表)   host =,才能“127.0.0.1",, #数据库ip   port =,才能“1521“,,,#端口   sid =,才能“test",, #数据库名称   dsn 才能=,cx_Oracle.makedsn(主机,港口,sid)   #才能斯科特是数据用户名,老虎是登录密码(默认用户名和密码)   时间=conn 才能;cx_Oracle.connect (“scott",,“tiger",, dsn)   #才能SQL语句,可以定制,实现灵活查询   时间=sql 才能;& # 39;select  *,得到& # 39;+表   #,才能使用pandas 的read_sql函数,可以直接将数据存放在dataframe中   时间=results 才能;pd.read_sql(康涅狄格州sql)   conn.close才能   return 才能结果   test_data =,查询(test_table), #,可以得到结果集

<强> 3。实现插入操作

#工具库导入   import  pandas  as  pd   import  cx_Oracle   #实现插入功能   def  input_to_db(数据表):   host =,才能“127.0.0.1",, #数据库ip   port =,才能“1521“,,,#端口   sid =,才能“test",, #数据库名称   dsn 才能=,cx_Oracle.makedsn(主机,港口,sid)   #才能斯科特是数据用户名,老虎是登录密码(默认用户名和密码)   时间=conn 才能;cx_Oracle.connect (“scott",,“tiger",, dsn)   #才能建立游标   时间=cursor 才能;connection.cursor ()   #才能sql语句,注意% s要加引号,否则会报ora - 01036错误   query =,才能“INSERT  INTO" +表+“(姓名、性别、年龄),VALUES  (& # 39; % & # 39;,, & # 39; % & # 39;,, & # 39; % & # 39;)“;   #才能逐行插入数据   for 才能小姐:拷贝范围(len(数据)):   ,,,的名字=,data.ix[0]我   ,,,性别=,data.ix[1]我   ,,,的年龄=,data.ix[2]我   ,,#,执行sql语句   ,,,cursor.execute (query  %,(姓名、性别、年龄))   connection.commit才能()   #,才能关闭游标   cursor.close才能()   connection.close才能()   #测试插入数据库   #测试数据集   test_data =, pd.DataFrame([[& # 39;小明& # 39;,& # 39;男& # 39;,18],[& # 39;小芳& # 39;,& # 39;女& # 39;,18]],index =,(1、2),列=[& # 39;名字# 39;& # 39;性别# 39;,& # 39;年龄# 39;])   #调用函数实现插入   input_to_db (test_data test_table1)

<强> 4。Python备份甲骨文数据库

# !/usr/bin/Python   #=utf - 8编码   import 线程   import 操作系统   import 时间   #用户名   时间=user  & # 39;用户名# 39;   #密码   时间=passwd  & # 39;密码# 39;   #备份保存路径   时间=savepath  & # 39;/home/oracle/orcl_bak/& # 39;   #要备份的表   时间=tables  & # 39;,表=部门,员工# 39;   #备份周期   circle  2.0=,   #备份命令   global  bak_command   时间=bak_command  & # 39; exp  & # 39; +用户+ & # 39;/& # 39;+ passwd  +, & # 39;,文件=& # 39;,+ savepath   def  orclBak ():   你才能=,time.strftime (& # 39; Y % - % - % d  % H: % m: % & # 39;)   command 才能=,bak_command  +,你+,& # 39;.dmp& # 39; +,表   ,print 命令   if 才能;os.system(命令),==,0:   ,,,print  & # 39;备份成功& # 39;   其他的才能:   ,,,print  & # 39;备份失败& # 39;   global 才能;t   t 才能=,threading.Timer(圆,,orclBak)   t.start才能()   t =, threading.Timer(圆,orclBak)   t.start ()

关于使用Python怎么对甲骨文数据库进行读写操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。

使用Python怎么对甲骨文数据库进行读写操作