Python操作MySQL数据库的三种方法总结

yipeiwu_com7年前Python基础

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 MySQLdb

def 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-8

import pymysql

def connectdb():
 print('连接到mysql服务器...')
 # 打开数据库连接
 # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
 db = pymysql.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()

运行结果:

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-python
pip install MySQL-python

(3) 使用 mysql.connector:

#!/usr/bin/env python
# coding=utf-8

import mysql.connector

def connectdb():
 print('连接到mysql服务器...')
 # 打开数据库连接
 # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
 db = mysql.connector.connect(user="hp", passwd="Hp12345.", database="TESTDB", use_unicode=True)
 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()

运行结果:

以上这篇Python操作MySQL数据库的三种方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python利用WMI实现ping命令的例子

WMI是Windows系统的一大利器,Python的win32api库提供了对WMI的支持,安装win32api即可使用 WMI。 本例通过WMI的WQL实现ping命令。 impo...

python利用requests库模拟post请求时json的使用教程

python利用requests库模拟post请求时json的使用教程

我们都见识过requests库在静态网页的爬取上展现的威力,我们日常见得最多的为get和post请求,他们最大的区别在于安全性上: 1、GET是通过URL方式请求,可以直接看到,明文传输...

Python文本统计功能之西游记用字统计操作示例

Python文本统计功能之西游记用字统计操作示例

本文实例讲述了Python文本统计功能之西游记用字统计操作。分享给大家供大家参考,具体如下: 一、数据 xyj.txt,《西游记》的文本,2.2MB 致敬吴承恩大师,4020行(段) 二...

Python操作Excel插入删除行的方法

1. 前言 由于近期有任务需要,要写一个能够处理Excel的脚本,实现的功能是,在A表格上其中一列,对字符串进行分组和排序,然后根据排序好的A表格以固定格式自动填写到B表格上。 开始写脚...

python 文件查找及内容匹配方法

需求:程序开发中有大量的接口,但在实际的使用中有一部分是没有使用的,在开发的程序中匹配这些接口名,找到哪些接口从没有使用过。将这些没有使用过的接口名保存下来。 代码结构: 结构解析: 1...