Python3 连接各类数据库(Mysql、Mssql、Oracle)

一、Mysql

1. 安装 PyMysql 库
pip3 install pymysql
2. 连接数据库的几种方法
connect()方法用于连接数据库

第一种:将各类字段写上

db = pymysql.connect(host="localhost", port=3306, user="root", passwd="root", db="Geek_Web", charset="utf8mb4")

第二种:省略字段

db = pymysql.connect(root,root, Geek_Web)

第三种:构建配置文件

config = { 

'host':'localhost',
'port':3306,
'user':'root',
'passwd':'root',
'db':'Geek_Web',
'charset':'utf8mb4',
}

db = pymysql.connect(**config)
3. 操作数据库
cursor = db.cursor()        # cursor() 方法获取操作游标
sql = "SELECT * FROM main"
cursor.execute(sql)         # 执行SQL语句
results = cursor.fetchall() # 获取所有记录列表
results = cursor.fetchone() # 获取一条记录列表
db.commit()                 # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
                                # 除了查询其他操作都需要保存执行
cursor.close()
db.close()                  # 关闭数据库连接
4. PyMysql 返回字典数据

PyMysql 默认返回是元组,有时候需要返回数据库的字段,需要把 Key 也返回及返回字典类型

# 在连接数据库时候加上 cursorclass 就可以数据库内容以字典格式返回
cursorclass=pymysql.cursors.DictCursor
5. 源码实例
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

# 安装PyMySQL
# sudo pip install PyMySQL

import pymysql


config = {

    'host':'localhost',
    'port':3306,
    'user':'root',
    'passwd':'root',
    'db':'Geek_Web',
    'charset':'utf8mb4',
    # 数据库内容以字典格式输出
    #'cursorclass':pymysql.cursors.DictCursor,
}

# 连接数据库
def Mysql():
    # 连接数据库
    #db = pymysql.connect(host="localhost", port=3306, user="root", passwd="root", db="Geek_Web", charset="utf8mb4")
    db = pymysql.connect(**config)
    #cursor()方法获取操作游标 
    cursor = db.cursor()

    try:

        return (db, cursor)

    except:

        print("数据库访问失败")

# 增
def Insert(db, cursor):
    sql = "insert into main(id, Tag, Name, Version, Introduce, Class, Worked_OS, Course_URL, Download_URL, Image_URL, Remarks_1, Remarks_2) \
     values (NULL, '软件编号', '软件名称', '软件版本', '软件简介', '软件类别', '运行环境', '教程地址', '下载地址', '图标地址', '备注1', '备注2')"
    # 执行SQL语句
    cursor.execute(sql)
    # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
    db.commit()

# 删
def Delect(db, cursor):
    sql = "DELETE FROM main WHERE Name = '修改后的名字'"
    cursor.execute(sql)
    db.commit()

# 查
def Select(db, cursor):
    sql = "SELECT * FROM main"
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()

    return results

# 改
def Update(db, cursor):
    sql = "UPDATE main SET Name = '修改后的名字' WHERE Remarks_2 = '备注2'"
    cursor.execute(sql)
    db.commit()

# 关闭数据库连接
def Close(db, cursor):
    cursor.close()
    db.close()

(db, cursor) = Mysql()
print("\n-------------数据库初始状态-------------")
print(Select(db, cursor))
Insert(db, cursor)
print("\n-------------数据库插入数据-------------")
print(Select(db, cursor))
Update(db, cursor)
print("\n-------------数据库修改数据-------------")
print(Select(db, cursor))
Delect(db, cursor)
print("\n-------------数据库删除数据-------------")
print(Select(db, cursor))
Close(db, cursor)
6. PyMysql 参数
connect() 参数
  • host 连接的数据库服务器主机名 默认为本地主机(localhost)
  • user 连接数据库的用户名 默认为当前用户
  • passwd 连接密码 没有默认值
  • db 连接的数据库名 没有默认值
  • conv 将文字映射到Python类型的字典默认为MySQLdb.converters.conversions
  • cursorclass cursor()使用的种类 默认值为MySQLdb.cursors.Cursor
  • compress 启用协议压缩功能
  • named_pipe 在windows中 与一个命名管道相连接
  • init_command 一旦连接建立 就为数据库服务器指定一条语句来运行
  • readdefaultfile 使用指定的MySQL配置文件
  • readdefaultgroup 读取的默认组
  • unix_socket 在unix中 连接使用的套接字 默认使用TCP
  • port 指定数据库服务器的连接端口 默认是3306
连接对象方法
  • 连接对象的 db.close() 方法可关闭数据库连接 并释放相关资源 
  • 连接对象的 db.cursor([cursorClass]) 方法返回一个指针对象 用于访问和操作数据库中的数据 
  • 连接对象的 db.begin() 方法用于开始一个事务 如果数据库的AUTOCOMMIT已经开启就关闭它 直到事务调用commit()和rollback()结束
  • 连接对象的 db.commit() 和db.rollback()方法分别表示事务提交和回退
指针对象方法
  • 指针对象的 cursor.close() 方法关闭指针并释放相关资源
  • 指针对象的 cursor.execute(query[,parameters]) 方法执行数据库查询
  • 指针对象的 cursor.fetchall() 可取出指针结果集中的所有行 返回的结果集一个元组(tuples)
  • 指针对象的 cursor.fetchmany([size=cursor.arraysize])从查询结果集中取出多行 我们可利用可选的参数指定取出的行数 
  • 指针对象的 cursor.fetchone() 从查询结果集中返回下一行
  • 指针对象的 cursor.arraysize 属性指定由cursor.fetchmany()方法返回行的数目 影响fetchall()的性能 默认值为1 
  • 指针对象的 cursor.rowcount 属性指出上次查询或更新所发生行数-1表示还没开始查询或没有查询到数据

二、Mssql

1. 安装 PyMssql 库
pip3 install pymysql
2. 连接数据库的方法

Mssql 用字典配置不可以用,connect() 用来连接数据库

db = pymssql.connect(host="192.0.0.200",user="ymyg",password="ymyg",database="Geek_Web")
3. 操作数据库

和 Mysql 操作方法一模一样,只不过将 PyMysql 改为 PyMssql 即可,参考上面 PyMssql

4. PyMssql 返回字典数据

只需要在连接数据库时候加上一个 as_dict 字段,将值改为 True 即可

db = pymssql.connect(host="192.0.0.200",user="ymyg",password="ymyg",database="Geek_Web",as_dict=True)
5. PyMssql 参数
connect() 参数
  • dsn 连接字符串 主要用于与之前版本的pymssql兼容
  • user 用户名
  • password 密码
  • trusted 布尔值 指定是否使用windows身份认证登陆
  • host 主机名
  • database 数据库
  • timeout 查询超时
  • login_timeout 登陆超时
  • charset 数据库的字符集
  • as_dict 布尔值 指定返回值是字典还是元组
  • max_conn 最大连接数
操作方法
  • close() 关闭游标
  • execute(operation) 执行操作
  • execute(operation params) 执行操作 可以提供参数进行相应操作
  • executemany(operation paramsseq) 执行操作 Paramsseq 为元组
  • fetchone() 在结果中读取下一行
  • fetchmany(size=None) 在结果中读取指定数目的行
  • fetchall() 读取所有行
  • nextset() 游标跳转到下一个数据集
其他方法
  • autocommit(status) 布尔值 指示是否自动提交事务 默认的状态是关闭的 如果打开 你必须调用commit()方法来提交事务
  • close() 关闭连接
  • cursor() 返回游标对象 用于查询和返回数据
  • commit() 提交事务
  • rollback() 回滚事务
  • pymssqlCursor类 用于从数据库查询和返回数据
  • rowcount 返回最后操作影响的行数 
  • connection 返回创建游标的连接对象
  • lastrowid 返回插入的最后一行
  • rownumber 返回当前数据集中的游标(通过索引)
6. PyMssql 配置文件

在开源库目录下找到 freetds.conf 打开

# $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same 
# name is found in the installation directory.  
#
# For information about the layout of this file and its settings, 
# see the freetds.conf manpage "man freetds.conf".  

# Global settings are overridden by those in a database
# server specific section
[global]
       # TDS protocol version
;tds version = 4.2

# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
;dump file = /tmp/freetds.log
;debug flags = 0xffff
# Command and connection timeouts
;timeout = 10

;connect timeout = 10

# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.  
# Try setting 'text size' to a more reasonable limit 
text size = 64512

# A typical Sybase server#newadd
[test_db]
      host = 127.0.0.1
      port = 1433
      tds version = 8.0
      client charset = GBK

一、Oracle

1. 安装 cx_Oracle 库
pip3 install cx_Oracle
2. 连接数据库的几种方法

第一种:Oracle 连接方法

db = cx_Oracle.connect('root/root@localhost: 1523/orcl')

第二种:省略字段连接方法

db = cx_Oracle.connect('root', 'root', 'localhost: 1523/orcl')

第三种:dsn 方法

makedsn(IP/HOST, PORT, TNSNAME)
dsn = cx_Oracle.makedsn('localhost','1523','orcl')
db = cx_Oracle.connect('root','root',dsn)
3. 操作数据库

和 Mysql 操作方法一模一样,只不过将 PyMysql 改为 cx_Oracle 即可,参考上面 PyMssql

4. PyMssql 返回字典数据

Oracle 返回字典类型比较麻烦,因为 cx_Oracle 没有集成,所以需要我们自己写返回字典的方法

cx_Oracle 的 Cursor 对象有一个属性 rowfactory 是是用来自定义查询结果的预处理方法的,定义一个闭包

def makedict(cursor):
     cols = [d[0] for d in cursor.description] 
     def createrow(*args):
         return dict(zip(cols, args))
     return createrow

并将其注册给游标对象的rowfactory属性 cursor.rowfactory = makedict(cursor) 得到的结果自动由元组转为字典了

但要注意,注册的动作需要在每次执行 cursor.execute 之后都重复一次。最终的方法是定义了一个类来继承 Cursor 对象,这样就不需要重复注册了

5. cx_Oracle 参数
>_< 翻遍了 Google 和 度娘 都没找到完整的参数,英文太烂、时间紧迫没时间看官方文档,望有吊大的知情人士望告知






连接 Mysql:http://www.jb51.net/article/103382.htm

连接 SqlServer:http://blog.csdn.net/wanzhuan2010/article/details/18844789

连接 Oracle:http://blog.csdn.net/baidu_15113429/article/details/53788520

Oracle 返回字典:http://blog.csdn.net/yilovexing/article/details/78042904

https://ask.helplib.com/1400253

  • 0
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值