一、python连接数据库
from django.test import TestCase
# Create your tests here.
import cx_Oracle
def main():
# 1.建立连接
conn = cx_Oracle.connect('******', '******', '******:******/xydb')
# 2.创建游标
cursor = conn.cursor()
# 3.执行SQL
res = cursor.execute('select cust_id,cust_name from lh_test')
# 4.获取数据
data = res.fetchall()
for cust_id, cust_name in data:
print(cust_name,cust_id)
# 5.关闭游标
cursor.close()
# 6.关闭连接
conn.close()
if __name__ == '__main__':
main()
关于Python3连接Oracle时报错"64-bit Oracle Client library cannot be loaded"解决方案
在已安装好cx_Oracle,通过客户端测试可连接的情况下报错如下:
cx_Oracle版本可在以下官网查询,对应到python,oracle的版本。
https://cx-oracle.readthedocs.io/en/latest/
问:
“cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "The specified module could not be found
".
答
官网下载:https://www.oracle.com/database/technologies/instant-client/winx64-64-downloads.html
解压后文件如下图
将解压后的文件中的dll文件复制到python文件中
测试通过输出结果
二、Django配置Oracle数据库
客户端连接测试,可按提示安装部分驱动
service_name
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'IP:端口号/service_name',
'USER': '用户名',
'PASSWORD': '密码',
}
}
SID
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '数据库SID',
'USER': '用户名',
'PASSWORD': '密码',
'HOST':'IP',
'PORT':'端口号'
}
}
Terminal 中下载pip install cx-Oracle
三、models.py
3.1
问
django在migrate时报错cx_Oracle.DatabaseError: ORA-02000: missing ALWAYS keyword
原因
从错误提示ORA-02000: missing ALWAYS keyword看,是SQL语法错误,创建表的时候使用了Always这个关键词。
Always是在Oracle12c的新特性自增序列里用到的,语法如下:
generated-column-spec
[ GENERATED {
ALWAYS | BY DEFAULT } AS IDENTITY
[ ( START WITH IntegerConstant
[ ,INCREMENT BY IntegerConstant] ) ] ] ]
但是,我机器上用的是Oracle11.2.0.4版本,这个语法在11g版本里执行自然就会报ORA-02000的错误
解决 方案主要有2种:
(1)将Oracle升级到12c
(2)将cx_oracle降低版本
注意选择方案(2)将cx_oracle降低版本后,接着出现了django版本与cx_oracle版本不适应的情况,接着又降低django版本,,依然bug,因本人将数据写入MySQL中,Oracle读取仅解决3.2问题,3.1问题可留给大家尝试。
查询Python版本 python
查询django版本 pip show django
查看cx_oracle版本pip show cx_oracle
3.2
问
inspectdb命令报错 ORA-00904: "IDENTITY_COLUMN": invalid identifier
原因分析见上
答
pip uninstall django
pip install Django==1.11.22
python manage.py inspectdb --database db_oracle lh_test >app/models.py
pip uninstall django
pip install Django==3.1.2