这篇文章主要介绍了三种python操作mysql数据库的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1. mysqldb 的使用
(1) 什么是mysqldb?
mysqldb 是用于 python 连接 mysql 数据库的接口,它实现了 python 数据库 api 规范 v2.0,基于 mysql c api 上建立的。
(2) 源码安装 mysqldb: https://pypi.python.org/pypi/mysql-python
$ tar zxvf mysql-python-*.tar.gz
$ cd mysql-python-*
$ python setup.py build
$ python setup.py install
(3) mysqldb 的使用:
#!/usr/bin/env python
# coding=utf-8
import mysqldbdef connectdb():
print('连接到mysql服务器...')
# 打开数据库连接
# 用户名:hp, 密码:hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库testdb,并在testdb数据库中创建好表student
db = mysqldb.connect("localhost","hp","hp12345.","testdb")
print('连接上了!')
return db
def createtable(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果存在表sutdent先删除
cursor.execute("drop table if exists student")
sql = """create table student (
id char(10) not null,
name char(8),
grade int )"""
# 创建sutdent表
cursor.execute(sql)
def insertdb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# sql 插入语句
sql = """insert into student
values ('001', 'czq', 70),
('002', 'lhq', 80),
('003', 'mq', 90),
('004', 'wh', 80),
('005', 'hp', 70),
('006', 'yf', 66),
('007', 'test', 100)"""
#sql = "insert into student(id, name, grade) \
# values ('%s', '%s', '%d')" % \
# ('001', 'hp', 60)
try: # 执行sql语句
cursor.execute(sql) # 提交到数据库执行
db.commit() except: # rollback in case there is any error
print '插入数据失败!'
db.rollback()def querydb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# sql 查询语句
#sql = "select * from student \
# where grade > '%d'" % (80)
sql = "select * from student"
try:
# 执行sql语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
grade = row[2] # 打印结果
print "id: %s, name: %s, grade: %d" % \
(id, name, grade)
except: print "error: unable to fecth data"def deletedb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 删除语句
sql = "delete from student where grade = '%d'" % (100) try: # 执行sql语句
cursor.execute(sql) # 提交修改
db.commit() except: print '删除数据失败!'
# 发生错误时回滚
db.rollback()def updatedb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 更新语句
sql = "update student set grade = grade + 3 where id = '%s'" % ('003') try: # 执行sql语句
cursor.execute(sql) # 提交到数据库执行
db.commit() except: print '更新数据失败!'
# 发生错误时回滚
db.rollback()def closedb(db):
db.close()def main():
db = connectdb() # 连接mysql数据库
createtable(db) # 创建表
insertdb(db) # 插入数据
print '\n插入数据后:'
querydb(db)
deletedb(db) # 删除数据
print '\n删除数据后:'
querydb(db)
updatedb(db) # 更新数据
print '\n更新数据后:'
querydb(db)
closedb(db) # 关闭数据库if __name__ == '__main__':
main()
运行结果:
2. pymysql 的使用
(1) 什么是 pymysql?
pymysql 是 python 中用于连接 mysql 服务器的一个库,它遵循 python 数据库 api 规范 v2.0,并包含了 pure-python mysql 客户端库。
(2) 安装 pymysql:
pip install pymysql
(3) 使用 pymysql:
#!/usr/bin/env python# coding=utf-8import pymysqldef connectdb():
print('连接到mysql服务器...') # 打开数据库连接
# 用户名:hp, 密码:hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库testdb,并在testdb数据库中创建好表student
db = pymysql.connect("localhost","hp","hp12345.","testdb")
print('连接上了!') return dbdef createtable(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # 如果存在表sutdent先删除
cursor.execute("drop table if exists student")
sql = """create table student (
id char(10) not null,
name char(8),
grade int )"""
# 创建sutdent表
cursor.execute(sql)def insertdb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 插入语句
sql = """insert into student
values ('001', 'czq', 70),
('002', 'lhq', 80),
('003', 'mq', 90),
('004', 'wh', 80),
('005', 'hp', 70),
('006', 'yf', 66),
('007', 'test', 100)"""
#sql = "insert into student(id, name, grade) \
# values ('%s', '%s', '%d')" % \
# ('001', 'hp', 60)
try: # 执行sql语句
cursor.execute(sql) # 提交到数据库执行
db.commit() except: # rollback in case there is any error
print '插入数据失败!'
db.rollback()def querydb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 查询语句
#sql = "select * from student \
# where grade > '%d'" % (80)
sql = "select * from student"
try: # 执行sql语句
cursor.execute(sql) # 获取所有记录列表
results = cursor.fetchall() for row in results:
id = row[0]
name = row[1]
grade = row[2] # 打印结果
print "id: %s, name: %s, grade: %d" % \
(id, name, grade) except: print "error: unable to fecth data"def deletedb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 删除语句
sql = "delete from student where grade = '%d'" % (100) try: # 执行sql语句
cursor.execute(sql) # 提交修改
db.commit() except: print '删除数据失败!'
# 发生错误时回滚
db.rollback()def updatedb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 更新语句
sql = "update student set grade = grade + 3 where id = '%s'" % ('003') try: # 执行sql语句
cursor.execute(sql) # 提交到数据库执行
db.commit() except: print '更新数据失败!'
# 发生错误时回滚
db.rollback()def closedb(db):
db.close()def main():
db = connectdb() # 连接mysql数据库
createtable(db) # 创建表
insertdb(db) # 插入数据
print '\n插入数据后:'
querydb(db)
deletedb(db) # 删除数据
print '\n删除数据后:'
querydb(db)
updatedb(db) # 更新数据
print '\n更新数据后:'
querydb(db)
closedb(db) # 关闭数据库if __name__ == '__main__':
main()
运行结果:
3. mysql.connector 的使用
(1) 什么是 mysql.connector?
由于 mysql 服务器以独立的进程运行,并通过网络对外服务,所以,需要支持 python 的 mysql 驱动来连接到 mysql 服务器。
目前,有两个 mysql 驱动:
mysql-connector-python:是 mysql 官方的纯 python 驱动;
mysql-python :是封装了 mysql c驱动的 python 驱动。
(2) 安装 mysql.connector:
pip install mysql-connector-pythonpip install mysql-python
(3) 使用 mysql.connector:
#!/usr/bin/env python# coding=utf-8import mysql.connectordef connectdb():
print('连接到mysql服务器...') # 打开数据库连接
# 用户名:hp, 密码:hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库testdb,并在testdb数据库中创建好表student
db = mysql.connector.connect(user="hp", passwd="hp12345.", database="testdb", use_unicode=true)
print('连接上了!') return dbdef createtable(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # 如果存在表sutdent先删除
cursor.execute("drop table if exists student")
sql = """create table student (
id char(10) not null,
name char(8),
grade int )"""
# 创建sutdent表
cursor.execute(sql)def insertdb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 插入语句
sql = """insert into student
values ('001', 'czq', 70),
('002', 'lhq', 80),
('003', 'mq', 90),
('004', 'wh', 80),
('005', 'hp', 70),
('006', 'yf', 66),
('007', 'test', 100)"""
#sql = "insert into student(id, name, grade) \
# values ('%s', '%s', '%d')" % \
# ('001', 'hp', 60)
try: # 执行sql语句
cursor.execute(sql) # 提交到数据库执行
db.commit() except: # rollback in case there is any error
print '插入数据失败!'
db.rollback()def querydb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 查询语句
#sql = "select * from student \
# where grade > '%d'" % (80)
sql = "select * from student"
try: # 执行sql语句
cursor.execute(sql) # 获取所有记录列表
results = cursor.fetchall() for row in results:
id = row[0]
name = row[1]
grade = row[2] # 打印结果
print "id: %s, name: %s, grade: %d" % \
(id, name, grade) except: print "error: unable to fecth data"def deletedb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 删除语句
sql = "delete from student where grade = '%d'" % (100) try: # 执行sql语句
cursor.execute(sql) # 提交修改
db.commit() except: print '删除数据失败!'
# 发生错误时回滚
db.rollback()def updatedb(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor() # sql 更新语句
sql = "update student set grade = grade + 3 where id = '%s'" % ('003') try: # 执行sql语句
cursor.execute(sql) # 提交到数据库执行
db.commit() except: print '更新数据失败!'
# 发生错误时回滚
db.rollback()def closedb(db):
db.close()def main():
db = connectdb() # 连接mysql数据库
createtable(db) # 创建表
insertdb(db) # 插入数据
print '\n插入数据后:'
querydb(db)
deletedb(db) # 删除数据
print '\n删除数据后:'
querydb(db)
updatedb(db) # 更新数据
print '\n更新数据后:'
querydb(db)
closedb(db) # 关闭数据库if __name__ == '__main__':
main()
运行结果:
以上就是三种python操作mysql数据库的方法的详细内容。
