Python3连接MySQL

Python连接MySQL的工具类

目前主要有以下这些

MySQLDB http://mysql-python.sourceforge.net/MySQLdb.html, https://github.com/farcepest/MySQLdb1, https://github.com/farcepest/moist

PyMySQL/mysqlclient-python https://github.com/PyMySQL/mysqlclient-python

PyMySQL/PyMySQL https://github.com/PyMySQL/PyMySQL

mysql-connector-python https://github.com/mysql/mysql-connector-python

其中, MySQLDB是用python包装的底层使用C写的连接器, 两个版本MySQLDB1, moist都已经不再更新.
mysqlclient-python 和 PyMySQL都是同一个作者维护的, 一个是基于C的连接器, 另一个是纯Python的连接器, 这个是现在用得最多的.
mysql-connector-python是Oracle官方团队写的一个纯python的连接器, 性能和PyMySQL差不多, 另外因为license问题不能直接通过PyPi安装.

如果对性能要求较高, 可以采用mysqlclient-python, 如果只是普通使用, 可以采用PyMySQL

PyMySQL的安装

pip3 install pymysql

使用PyMySQL

查单条

import pymysql

db = pymysql.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print ("Database version : %s " % data)
db.close()

查多条

import pymysql

db = pymysql.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE WHERE INCOME > %s" % (1000)

try:
   cursor.execute(sql)
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fetch data")

db.close()

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('[email protected]', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('[email protected]',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

.

注意事项

1. 在sql中如果出现了 % 符号作为sql的一部分, 但是在execute时又需要带入参数, 这时候会出现 ValueError: unsupported format character 错误. 因为pymysql会错误的认为这个%符号是未正确拼写的格式化字符串的一部分. 这时候需要将 % 转义, 写为 %%. 例如

  CASE CAST(SUBSTRING(u.identity_number, 17, 1) AS SIGNED) %% 2
    WHEN 0 THEN '女'
    ELSE '男'
  END `gender`,

 

你可能感兴趣的:(Python3连接MySQL)