在我刚开始学python的时候,用的是python2.7,那时候连接mysql用的库是MySQLdb(很诡异的大小写,初学者经常因为记不住大小写导致“No module named xxx”)。燃鹅,在python3中,这个库已经不能继续使用了。怎么办呢?在python3中,可以使用pymysql或mysqlclient。今天我要介绍的就是pymysql。
用pymysql代替MySQLdb
pymysql安装(python连接mysql)
pip3 install pymysql
安装成功
/usr/local/lib/python3.5/dist-packages
会看到
PyMySQL-0.7.11.dist-info
pymysql
如果使用pycharm 直接对应的python版本下在settings上安装插件即可
超级方便
使用pymysql操作sql
#!/usr/bin/env pytho
# -*- coding:utf-8 -*-
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='database_name', charset='utf8')
# 创建游标
cursor = conn.cursor()
# 执行SQL,并返回收影响行数
effect_row = cursor.execute("select * from tabe_name")
# 执行SQL,并返回受影响行数
#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,))
# 执行SQL,并返回受影响行数,执行多次
#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u1","u1pass","11111"),("u2","u2pass","22222")])
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
创建数据表
# 打开数据库连接
db = pymysql.connect(host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'root',
db='users',
charset = 'utf8')
#创建游标对象
cursor = db.cursor()
#使用 execute()方法执行SQL, 如果表存在则删除
cursor.execute("drop table IF EXISTS employee")
# 使用预处理语句创建表
sql = '''
create table employee(
id int PRIMARY KEY NOT NULL auto_increment,
name CHAR(20) not null,
passwd CHAR(20),
age int,
sex char(1)
)
'''
cursor.execute(sql)
# 提交到数据库执行
db.commit()
#关闭游标 关闭数据库连接
cursor.close()
db.close()
插入数据
sql = "select * from employee \
where id = '%d'" \
% (1)
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
passwd = row[2]
age = row[3]
sex = row[4]
print("id=%d, name=%s, passwd=%s, age=%d, sex=%c" % \
(id,name,passwd,age,sex))
except:
print("Error: unable to fetch data")
cursor.close()
db.close()
更新数据
#更新操作
sql = "update employee set age = age + 1 where sex = '%c'"\
% ('M')
try:
effect_row = cursor.execute(sql)
print("effect_row:",effect_row)
db.commit()
except:
db.rollback()
cursor.close()
db.close()
删除数据
# SQL 删除语句
sql = "delete from employee where age = 20"
print("1")
try:
# 执行SQL语句
effect_row = cursor.execute(sql)
print("effect_row:" , effect_row)
# 提交修改
db.commit()
except:
print("except")
# 发生错误时回滚
db.rollback()