# -*- coding: utf-8 -*-
import cx_Oracle
def interact_db(userInfo,dbStr,sql):
connStr = userInfo + dbStr
conn = cx_Oracle.connect(connStr)
c = conn.cursor()
c.execute(sql)
if sql.startswith('select'):
fir=c.fetchall()
conn.commit()
c.close()
conn.close()
return fir
else:
conn.commit()
c.close()
conn.close()
def exec_sql(userInfo,dbStr,sql):
if sql.startswith('select'):
results = interact_db(userInfo,dbStr,sql)
return results
else:
interact_db(userInfo,dbStr,sql)
userInfo这个变量里存的是用户信息,格式为'用户名/密码';
dbStr变量里存的是数据库连接字符串,格式为'@HOST:PORT/SERVICE_NAME'。例子如下:dbStr = '@20.129.340.851:8885/test'用户名密码后面那些信息(数据库连接字符串)可在本地oracle客户端文件夹下的“TNSNAMES.ORA”文件中查看,如下图位置所示:
userInfo = 'userName/passWord'
之后在其他的脚本中就可以调用这个数据库访问脚本来实现对数据库的操作了。例子如下:
# -*- coding: utf-8 -*-
from execute_sql import exec_sql
dbStr = '@HOST:PORT/SERVICE_NAME'
userInfo = 'username/password'
#查询
dbSql = 'select xx from xxx where a like \'%aaa%\''
r = exec_sql(userInfo,dbStr,dbSql)
tip = u'XXXXXXX:'+r[0][0]