python3连接数据库mysql、oracle

python3连接数据操作,需要导入另外的模块,类似与Java中导入jar包。

连接mysql需要导入pymysql,连接oracle需要导入cx_Oracle,这两个模块python是不自带的,需要自己手动安装。

cx_Oracle与pymysql安装:

   使用pyCharm开发工具安装:File -->Setting -->Project:xxx -->Project Interperter

   点击右边 + 号,弹出框内搜索cx_Oracle或pymysql,选中后点击左下角Install Package安装,

  成果后显示Package 'cx_Oracle' Install successfully表示安装成功。

  手动安装或者Linux安装,网上下载:

    cx_Oracle下载地址:https://pypi.python.org/pypi/cx_Oracle/

    pymysql下载地址:https://github.com/PyMySQL/PyMySQL


代码:

import pymysql
import cx_Oracle

def testMysql1():
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='pure')
    cu = conn.cursor()
    cu.execute("select * from user")
    res = cu.fetchall()
    print(res)
    cu.close()
    conn.close()

def testOracle():
    #python安装的是多少位oracle客户端(instantclient_11_2)就是多少位
    #conn = cx_Oracle.connect('用户名/密码@数据库ip:端口号/数据库名')
    conn = cx_Oracle.connect('root/123456@127.0.0.1:1521/testDB')
    curs = conn.cursor()
    rr = curs.execute('select sysdate from dual')
    row = curs.fetchone()
    print(row[0])
    curs.close()
    conn.close()
注意数据库bit需要与Python一致,如Python是win64,数据库要求也需要win64,不然会报错,如:

cx_Oracle.DatabaseError:DPI-1047: 64-bit Oracle Client library cannot be loaded:

"E:\Oracle\plsql_win64\instantclient_11_2\oci.dll is not the correct architecture".

See https://oracle.github.io/odpi/doc/installation.html#windows for help

这个就是python与oracle版本不一致导致,去提示连接下载个64位的







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值