python3 操作mysql数据库(mysql.connector 和 pymysql )

左手的ㄟ右手 2021-07-28 12:19 694阅读 0赞

1. PyMySQL 的使用

(1) 什么是 PyMySQL?

  PyMySQL 是 Python 中用于连接 MySQL 服务器的一个库,它遵循 Python 数据库 API 规范 V2.0,并包含了 pure-Python MySQL 客户端库。

(2) 安装 PyMysql:

  1. pip install PyMysql

(3) 参数说明:

  1. pymysql.Connect()参数说明
  2. host(str): MySQL服务器地址
  3. port(int): MySQL服务器端口号
  4. user(str): 用户名
  5. passwd(str): 密码
  6. db(str): 数据库名称
  7. charset(str): 连接编码
  8. connection对象支持的方法
  9. cursor() 使用该连接创建并返回游标
  10. commit() 提交当前事务
  11. rollback() 回滚当前事务
  12. close() 关闭连接
  13. cursor对象支持的方法
  14. execute(op) 执行一个数据库的查询命令
  15. fetchone() 取得结果集的下一行
  16. fetchmany(size) 获取结果集的下几行
  17. fetchall() 获取结果集中的所有行
  18. rowcount() 返回数据条数或影响行数
  19. close() 关闭游标对象

(4) 使用 PyMySQL:

  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. import pymysql
  4. def connectdb():
  5. print('连接到mysql服务器...')
  6. # 打开数据库连接
  7. # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
  8. db = pymysql.connect("localhost","hp","Hp12345.","TESTDB")
  9. print('连接上了!')
  10. return db
  11. def createtable(db):
  12. # 使用cursor()方法获取操作游标
  13. cursor = db.cursor()
  14. # 如果存在表Sutdent先删除
  15. cursor.execute("DROP TABLE IF EXISTS Student")
  16. sql = """CREATE TABLE Student (
  17. ID CHAR(10) NOT NULL,
  18. Name CHAR(8),
  19. Grade INT )"""
  20. # 创建Sutdent表
  21. cursor.execute(sql)
  22. def insertdb(db):
  23. # 使用cursor()方法获取操作游标
  24. cursor = db.cursor()
  25. # SQL 插入语句
  26. sql = """INSERT INTO Student
  27. VALUES ('001', 'CZQ', 70),
  28. ('002', 'LHQ', 80),
  29. ('003', 'MQ', 90),
  30. ('004', 'WH', 80),
  31. ('005', 'HP', 70),
  32. ('006', 'YF', 66),
  33. ('007', 'TEST', 100)"""
  34. #sql = "INSERT INTO Student(ID, Name, Grade) \
  35. # VALUES ('%s', '%s', '%d')" % \
  36. # ('001', 'HP', 60)
  37. try:
  38. # 执行sql语句
  39. cursor.execute(sql)
  40. # 提交到数据库执行
  41. db.commit()
  42. except:
  43. # Rollback in case there is any error
  44. print '插入数据失败!'
  45. db.rollback()
  46. def querydb(db):
  47. # 使用cursor()方法获取操作游标
  48. cursor = db.cursor()
  49. # SQL 查询语句
  50. #sql = "SELECT * FROM Student \
  51. # WHERE Grade > '%d'" % (80)
  52. sql = "SELECT * FROM Student"
  53. try:
  54. # 执行SQL语句
  55. cursor.execute(sql)
  56. # 获取所有记录列表
  57. results = cursor.fetchall()
  58. for row in results:
  59. ID = row[0]
  60. Name = row[1]
  61. Grade = row[2]
  62. # 打印结果
  63. print "ID: %s, Name: %s, Grade: %d" % \
  64. (ID, Name, Grade)
  65. except:
  66. print "Error: unable to fecth data"
  67. def deletedb(db):
  68. # 使用cursor()方法获取操作游标
  69. cursor = db.cursor()
  70. # SQL 删除语句
  71. sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)
  72. try:
  73. # 执行SQL语句
  74. cursor.execute(sql)
  75. # 提交修改
  76. db.commit()
  77. except:
  78. print '删除数据失败!'
  79. # 发生错误时回滚
  80. db.rollback()
  81. def updatedb(db):
  82. # 使用cursor()方法获取操作游标
  83. cursor = db.cursor()
  84. # SQL 更新语句
  85. sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')
  86. try:
  87. # 执行SQL语句
  88. cursor.execute(sql)
  89. # 提交到数据库执行
  90. db.commit()
  91. except:
  92. print '更新数据失败!'
  93. # 发生错误时回滚
  94. db.rollback()
  95. def closedb(db):
  96. db.close()
  97. def main():
  98. db = connectdb() # 连接MySQL数据库
  99. createtable(db) # 创建表
  100. insertdb(db) # 插入数据
  101. print '\n插入数据后:'
  102. querydb(db)
  103. deletedb(db) # 删除数据
  104. print '\n删除数据后:'
  105. querydb(db)
  106. updatedb(db) # 更新数据
  107. print '\n更新数据后:'
  108. querydb(db)
  109. closedb(db) # 关闭数据库
  110. if __name__ == '__main__':
  111. main()

运行结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3doYXRkYXk_size_16_color_FFFFFF_t_70

实例2:

  1. import pymysql.cursors
  2. # 连接数据库
  3. connect = pymysql.connect(
  4. host='localhost',
  5. port=3310,
  6. user='woider',
  7. passwd='3243',
  8. db='python',
  9. charset='utf8'
  10. )
  11. # 获取游标
  12. cursor = connect.cursor()
  13. # 插入数据
  14. sql = "INSERT INTO trade (name, account, saving) VALUES ( '%s', '%s', %.2f )"
  15. data = ('雷军', '13512345678', 10000)
  16. cursor.execute(sql % data)
  17. connect.commit()
  18. print('成功插入', cursor.rowcount, '条数据')
  19. # 修改数据
  20. sql = "UPDATE trade SET saving = %.2f WHERE account = '%s' "
  21. data = (8888, '13512345678')
  22. cursor.execute(sql % data)
  23. connect.commit()
  24. print('成功修改', cursor.rowcount, '条数据')
  25. # 查询数据
  26. sql = "SELECT name,saving FROM trade WHERE account = '%s' "
  27. data = ('13512345678',)
  28. cursor.execute(sql % data)
  29. for row in cursor.fetchall():
  30. print("Name:%s\tSaving:%.2f" % row)
  31. print('共查找出', cursor.rowcount, '条数据')
  32. # 删除数据
  33. sql = "DELETE FROM trade WHERE account = '%s' LIMIT %d"
  34. data = ('13512345678', 1)
  35. cursor.execute(sql % data)
  36. connect.commit()
  37. print('成功删除', cursor.rowcount, '条数据')
  38. # 事务处理
  39. sql_1 = "UPDATE trade SET saving = saving + 1000 WHERE account = '18012345678' "
  40. sql_2 = "UPDATE trade SET expend = expend + 1000 WHERE account = '18012345678' "
  41. sql_3 = "UPDATE trade SET income = income + 2000 WHERE account = '18012345678' "
  42. try:
  43. cursor.execute(sql_1) # 储蓄增加1000
  44. cursor.execute(sql_2) # 支出增加1000
  45. cursor.execute(sql_3) # 收入增加2000
  46. except Exception as e:
  47. connect.rollback() # 事务回滚
  48. print('事务处理失败', e)
  49. else:
  50. connect.commit() # 事务提交
  51. print('事务处理成功', cursor.rowcount)
  52. # 关闭连接
  53. cursor.close()
  54. connect.close()

2. mysql.connector 的使用

(1) 什么是 mysql.connector?

  由于 MySQL 服务器以独立的进程运行,并通过网络对外服务,所以,需要支持 Python 的 MySQL 驱动来连接到 MySQL 服务器。

目前,有两个 MySQL 驱动:

mysql-connector-python:是 MySQL 官方的纯 Python 驱动;

MySQL-python :是封装了 MySQL C驱动的 Python 驱动。

(2) 安装 mysql.connector:

  1. pip install mysql-connector-python
  2. pip install MySQL-python

(3) 使用 mysql.connector:

  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. import mysql.connector
  4. def connectdb():
  5. print('连接到mysql服务器...')
  6. # 打开数据库连接
  7. # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
  8. db = mysql.connector.connect(user="hp", passwd="Hp12345.", database="TESTDB", use_unicode=True)
  9. print('连接上了!')
  10. return db
  11. def createtable(db):
  12. # 使用cursor()方法获取操作游标
  13. cursor = db.cursor()
  14. # 如果存在表Sutdent先删除
  15. cursor.execute("DROP TABLE IF EXISTS Student")
  16. sql = """CREATE TABLE Student (
  17. ID CHAR(10) NOT NULL,
  18. Name CHAR(8),
  19. Grade INT )"""
  20. # 创建Sutdent表
  21. cursor.execute(sql)
  22. def insertdb(db):
  23. # 使用cursor()方法获取操作游标
  24. cursor = db.cursor()
  25. # SQL 插入语句
  26. sql = """INSERT INTO Student
  27. VALUES ('001', 'CZQ', 70),
  28. ('002', 'LHQ', 80),
  29. ('003', 'MQ', 90),
  30. ('004', 'WH', 80),
  31. ('005', 'HP', 70),
  32. ('006', 'YF', 66),
  33. ('007', 'TEST', 100)"""
  34. #sql = "INSERT INTO Student(ID, Name, Grade) \
  35. # VALUES ('%s', '%s', '%d')" % \
  36. # ('001', 'HP', 60)
  37. try:
  38. # 执行sql语句
  39. cursor.execute(sql)
  40. # 提交到数据库执行
  41. db.commit()
  42. except:
  43. # Rollback in case there is any error
  44. print '插入数据失败!'
  45. db.rollback()
  46. def querydb(db):
  47. # 使用cursor()方法获取操作游标
  48. cursor = db.cursor()
  49. # SQL 查询语句
  50. #sql = "SELECT * FROM Student \
  51. # WHERE Grade > '%d'" % (80)
  52. sql = "SELECT * FROM Student"
  53. try:
  54. # 执行SQL语句
  55. cursor.execute(sql)
  56. # 获取所有记录列表
  57. results = cursor.fetchall()
  58. for row in results:
  59. ID = row[0]
  60. Name = row[1]
  61. Grade = row[2]
  62. # 打印结果
  63. print "ID: %s, Name: %s, Grade: %d" % \
  64. (ID, Name, Grade)
  65. except:
  66. print "Error: unable to fecth data"
  67. def deletedb(db):
  68. # 使用cursor()方法获取操作游标
  69. cursor = db.cursor()
  70. # SQL 删除语句
  71. sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)
  72. try:
  73. # 执行SQL语句
  74. cursor.execute(sql)
  75. # 提交修改
  76. db.commit()
  77. except:
  78. print '删除数据失败!'
  79. # 发生错误时回滚
  80. db.rollback()
  81. def updatedb(db):
  82. # 使用cursor()方法获取操作游标
  83. cursor = db.cursor()
  84. # SQL 更新语句
  85. sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')
  86. try:
  87. # 执行SQL语句
  88. cursor.execute(sql)
  89. # 提交到数据库执行
  90. db.commit()
  91. except:
  92. print '更新数据失败!'
  93. # 发生错误时回滚
  94. db.rollback()
  95. def closedb(db):
  96. db.close()
  97. def main():
  98. db = connectdb() # 连接MySQL数据库
  99. createtable(db) # 创建表
  100. insertdb(db) # 插入数据
  101. print '\n插入数据后:'
  102. querydb(db)
  103. deletedb(db) # 删除数据
  104. print '\n删除数据后:'
  105. querydb(db)
  106. updatedb(db) # 更新数据
  107. print '\n更新数据后:'
  108. querydb(db)
  109. closedb(db) # 关闭数据库
  110. if __name__ == '__main__':
  111. main()

运行结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3doYXRkYXk_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,694人围观)

还没有评论,来说两句吧...

相关阅读