Python连接MySQL


PyMySQL 模块

PyMySQL是在 Python3.x 版本中用于连接 MySQL 服务器的一个第三方库,安装使用步骤如下:

pip install pymysql
!pip install pymysql
Looking in indexes: https://repo.huaweicloud.com/repository/pypi/simple
/usr/share/python-wheels/urllib3-1.25.8-py2.py3-none-any.whl/urllib3/connectionpool.py:999: InsecureRequestWarning: Unverified HTTPS request is being made to host 'repo.huaweicloud.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
Collecting pymysql
/usr/share/python-wheels/urllib3-1.25.8-py2.py3-none-any.whl/urllib3/connectionpool.py:999: InsecureRequestWarning: Unverified HTTPS request is being made to host 'repo.huaweicloud.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  Downloading https://repo.huaweicloud.com/repository/pypi/packages/4f/52/a115fe175028b058df353c5a3d5290b71514a83f67078a6482cff24d6137/PyMySQL-1.0.2-py3-none-any.whl (43 kB)
     |████████████████████████████████| 43 kB 38.1 MB/s eta 0:00:01
[?25hInstalling collected packages: pymysql
Successfully installed pymysql-1.0.2
import pymysql
# 连接MySQL   host='localhost'  password='Python@123'  user='py'   db='school'
# create user 'py'@'%' identified by 'Python@123';
# create database school charset utf8mb4;
# grant all privileges on school.* to 'py'@'%';
# flush privileges;

conn = pymysql.Connection(
    host = '127.0.0.1',
    user = 'py',
    password = 'Python@123',
    database = 'school',
    charset = 'utf8mb4'
)
cur = conn.cursor()
cur.execute('show databases;')
2
cur.fetchall()
(('information_schema',), ('school',))
cur.close()
conn.close()