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安装,网上下载。
代码:
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:Oracleplsql_win64instantclient_11_2oci.dll is not the correct architecture".
See https://oracle.github.io/odpi/doc/installation.html#windows for help
这个就是python与oracle版本不一致导致,去提示连接下载个64位的