Python MySQL 数据库连接不同方式

PyMySQL 驱动连接

什么是 PyMySQL?
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

PyMySQL 安装
在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。

PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL。

如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:

$ pip3 install PyMySQL
如果你的系统不支持 pip 命令,可以使用以下方式安装:

1、使用 git 命令下载安装包安装(你也可以手动下载):

$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install
2、如果需要制定版本号,可以使用 curl 命令来安装:

$ # X.X 为 PyMySQL 的版本号
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python3 setup.py install
$ # 现在你可以删除 PyMySQL* 目录
注意:请确保您有root权限来安装上述模块。

实例:
以下实例链接 Mysql 的 TESTDB 数据库:

实例(Python 3.0+)
#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

print ("Database version : %s " % data)

# 关闭数据库连接
db.close()

mysql-connector 驱动

mysql-connector 是 MySQL 官方提供的驱动器。

我们可以使用 pip 命令来安装 mysql-connector:

python -m pip install mysql-connector
使用以下代码测试 mysql-connector 是否安装成功:

demo_mysql_test.py:
import mysql.connector
执行以上代码,如果没有产生错误,表明安装成功。

创建数据库连接
可以使用以下代码来连接数据库:

demo_mysql_test.py:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost", # 数据库主机地址
user="yourusername", # 数据库用户名
passwd="yourpassword" # 数据库密码
)

print(mydb)

MySQLdb库来连接

MySQLdb先支持Python2.,不支持Python3.。

MySQLdb的安装
MySQLdb的安装可以使用pip进行安装:

pip install MySQL-python==1.2.5

Python对MySQL进行操作
Python与MySQL进行连接-connection
创建连接的对象,建立Python客户端与数据库网络连接
创建的基本方法MySQLdb.connect(相关的参数),其中的主要参数有(host, user, passwd, port, db, charset),在这些参数中,只有port是数字类型,其他的参数都是字符串类型。
对数据库进行执行,获取执行的结构-cursor
游标对象:用于执行查询和获取结果
cursor对象包含的方法如下:
参数名 说明
execute(command) 执行一个数据库查询和命令
fetchone() 获取结果集中的下一行
fetchmany() 获取结果集中的下几行
fetchall() 获取结果集中的全部信息
rowcount 最近的一次execute返回数据或影响的行数
close() 关闭游标对象
举一个例子

import MySQLdb
conn = MySQLdb.Connect(
host = "127.0.0.1",
port = 3306,
user = "lee",
passwd = "123",
db = "lee",
charset = "utf8",
)

cursor = conn.cursor()

sql_command = 'select * from user'

cursor.execute(sql_command)

rs = cursor.fetchall()


for ele in rs:
print 'userid : %d , username : %s' %ele

cursor.close()
conn.close()

让python 3支持mysqldb的解决方法

原因
MySQLdb 只适用于python2.x,发现pip装不上。它在py3的替代品是: import pymysql

pip install pymysql
django+mysql
而Django默认的还是使用MySQLdb:执行会报:ImportError: No module named 'MySQLdb'

解决:
在站点的 __init__.py 文件中添加

import pymysql
pymysql.install_as_MySQLdb()

在使用torndb的过程中发现其底层是对MySQLdb的封装,而MySQLdb不支持python3.x
解决:安装mysqlclient包,其完全兼容MySQLdb
pip install mysqlclient

解决了MySQLdb问题后,使用torndb的query功能是报了新的错误,如下:


AttributeError: module 'itertools' has no attribute 'izip'


源代码:

#! /usr/bin env python3
# -*- coding:utf-8 -*-

import torndb

config = {
"host": "127.0.0.1:3306",
"user": "root",
"password": "bukeshuo",
"database": "db_test"
}
def query_all():
con = torndb.Connection(**config)
results = con.query('select account from users')
con.close()
return results

print(query_all())

 

解决方案:更改con.query()中的源代码。(按住ctrl点击con.query 目的是找到这个模块的源代码)
按照下面的提示进行更改,并保存。

def query(self, query, *parameters, **kwparameters):
"""Returns a row list for the given query and parameters."""
cursor = self._cursor()
try:
self._execute(cursor, query, parameters, kwparameters)
column_names = [d[0] for d in cursor.description]
"""
错误说itertools找不到izip模块。
因为我们使用的mysqlclient替代MySQLdb,
所以使用zip_longest模块替代izip模块。
"""
# 使用这一句替代下面一行代码
# return [Row(itertools.zip_longest(column_names, row)) for row in cursor]
return [Row(itertools.izip(column_names, row)) for row in cursor]
finally:
cursor.close()

 

转载于:https://www.cnblogs.com/dingjiaoyang/p/11004404.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值