Python3 MySQL(mysql-connector)

用 mysql-connector-python 连接 MySQL:建连、建表、插入、查询与参数化。

Intermediate
Key Points连接用完要 close,写入必须 commit;SQL 一律用 %s 占位符传参,绝不用字符串拼接。

安装 mysql-connector

Oracle's mysql-connector-python is pure Python with no build step. PyMySQL is an alternative with nearly identical API — swap the import name.

Python
cmds = [
    "pip install mysql-connector-python",
    "pip install PyMySQL",
]

for c in cmds:
    print(c)
print(len(cmds))
Output
pip install mysql-connector-python
pip install PyMySQL
2
The examples below need a reachable MySQL server; running them as-is will fail to connect. Adjust host, user and password first.

创建数据库连接

mysql.connector.connect(host, user, password, database) opens a connection and cursor() gives you a handle to run SQL. In production use a pool and set timeouts.

Python
# import mysql.connector   # 需要先 pip install mysql-connector-python

config = {
    'host': 'localhost',
    'user': 'root',
    'password': 'your_password',
    'database': 'testdb',
    'connection_timeout': 5,
}

# 真实运行时:
# conn = mysql.connector.connect(**config)
# print(conn.is_connected())

print(sorted(config))
print(config['host'])
Output
['connection_timeout', 'database', 'host', 'password', 'user']
localhost

创建数据库表

Run DDL through cursor.execute(). Table and column names cannot be parameters — they must come from a whitelist in code — while values always use %s placeholders.

Python
DDL = """
CREATE TABLE IF NOT EXISTS sites (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(64) NOT NULL,
    url  VARCHAR(255) NOT NULL,
    UNIQUE KEY uk_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""

print(DDL.count('CREATE'))
print('utf8mb4' in DDL)
print('PRIMARY KEY' in DDL)
Output
1
True
True

插入数据

Writes need an explicit commit() — otherwise the change rolls back when the connection closes. Use executemany(sql, params) for bulk inserts; it is far faster than looping.

Python
INSERT = "INSERT INTO sites (name, url) VALUES (%s, %s)"

rows = [('runoob', 'https://www.runoob.com'), ('python', 'https://python.org')]

# 真实运行时:
# cursor.executemany(INSERT, rows)
# conn.commit()
# print(cursor.rowcount)

print(INSERT.count('%s'))
print(len(rows))
print(rows[0][0])
Output
2
2
runoob
%s here is the driver's placeholder, not Python string formatting. Writing "... %s" % value concatenates the value in and opens the door to SQL injection.

查询数据

fetchone() returns one row, fetchall() all rows, fetchmany(n) n rows — as tuples. Pass cursor(dictionary=True) to get dicts instead.

Python
SELECT = "SELECT id, name FROM sites WHERE name = %s"

# 真实运行时:
# cursor.execute(SELECT, ('runoob',))
# print(cursor.fetchone())
# cursor.execute("SELECT id, name FROM sites")
# print(cursor.fetchall())

sample = [(1, 'runoob'), (2, 'python')]
print(sample[0])
print([r[1] for r in sample])
Output
(1, 'runoob')
['runoob', 'python']

Friends & Partners