Python操作Oracle、MySQL、MsSQL、PostgreSql数据库

Python操作Oracle、MySQL、MsSQL、PostgreSql数据库:

1、模块: cx_Oracle,pymysql, pymssql,psycopg2

2、使用Python的DB-API操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection;
连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果,打开后一定记得关闭。
使用Cursor对象执行insert,update,delete语句时,执行结果由rowcount返回影响的行数,就可以拿到执行结果。
使用Cursor对象执行select语句时,通过fetchall()可以拿到结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录。
如果SQL语句带有参数,那么需要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:
cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password')),占位符的格式一般为“%s”%value,Oracle有点特殊使用“:s”{"s":value}。

  操作步骤:

  • 连接:connect
  • 取得游标:cursor
  • 执行命令:execute
  • 取得结果:fetchall fetchone rowcount
  • 关闭游标和连接:close

3、代码:

    

import cx_Oracle, pymysql,pymssql,psycopg2,sqlite3
import os

path = os.getcwd()
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' # 设置Oracle编码为简体中文,此点非常重要
#数据库连接
conn_oracle = cx_Oracle.connect('xxxxx/123456@localhost:1521/orcl') #'用户名/密码@主机ip地址/orcl'
conn_mysql= pymysql.connect(host='localhost', port=3306, user='xxxxx', password='123456', database='dbname',use_unicode=True, charset="utf8")
conn_mssql = pymssql.connect(host='localhost', port='1431', user='xxxx', password='123456', database='dbname')
conn_postgresql = psycopg2.connect( host="localhost", port="5866", user="xxxx", password="123456",database="dbname")
conn_sqlite = sqlite3.connect(
path + 'tables.db') #sqlite数据库就是一个.db后缀的文件

cur_oracle = conn_oracle.cursor() # 打开游标
cur_mysql = conn_mysql.cursor() # 打开游标
cur_mssql = conn_mssql.cursor() # 打开游标
cur_postgresql = conn_postgresql.cursor() # 打开游标
cur_sqlite = conn.cursor() #打开游标

#查询操作
sSQL ="SELECT * FROM dbname where name='%s'"#执行sql,获取所有数据
cur_mssql.execute(sSQL,'name')
result_str=cur_mssql.fetchall() #输出所有结果
result_str=cur_mssql.fetchone() #取一行结果
row_count=cur_mssql.rowcount#取得总行数
print('总行数:'+ str(row_count))

#执行数据操作
cur_oracle.execute('insert into dbname VALUES(:s0,:s1,:s2)’,{'s0':r0,'s1':r1,'s2':r2}) #cx_oracle操作oracle使用字典的形式
cur_mysql.execute('insert into dbname VALUES(%s,%s,%s)’,(r1,r2,r3))#pymysql操作mysql使用占位符的方法
cur_mssql.execute('insert into dbname VALUES(%s,%s,%s)’,(r1,r2,r3))#pymssql操作mssql使用占位符的方法
cur_postgresql.execute("insert into dbname values (%s, %s)", (who, age)) #psycopg2操作postgresql使用占位符的用法
cur_sqlite.execute('insert into dbname values(?,?)',(i,line)) #占位符

conn_mssql.commit() # 提交作业
cur_mssql.close() #关闭游标
conn_mssql.close() #关闭连接
cur_sqlite.close()

 

4、注意事项:

  • 数据库的编码问题:在不同数据库系统中,对字符的编码设定不一,需要特别注意。
  • 在不同数据库之间转换数据时,有不同的类型定义、字段长度的计算。
  • 特别需要注意对非法字符的处理。
  • 执行sql操作后返回的结果是一个元组,如果需要对字段进行处理,需要先转换成列表,再对列表的字段进行处理。  
for row in result_all:  # 取每条记录
    list_row=list(row) #从数据库中取到的每条记录是一个元组,需要转换成列表list
    i=[] #准备一个空列表
    for j in list_row: #循环每条记录的字段
        if type(j)==str: # 如果是字符串
            j=j.strip().replace(' ','').replace('\u3000','').replace('\x000','') #去掉空格和控制符,可以继续增加replace()进行处理
        i.append(j) #生成新的列表 

posted on 2020-01-07 10:31  sdlyxyf  阅读(420)  评论(0编辑  收藏  举报

导航