天天看点

Python:mysql-connector-python模块对MySQL数据库进行增删改查读操作

MySQL文档: https://dev.mysql.com/doc/connector-python/en/ PYPI: https://pypi.org/project/mysql-connector-python/

mysql-connector-python 是MySQL官方的Python语言MySQL连接模块

安装

$ pip install mysql-connector-python      

代码示例

连接管理

# -*- coding: utf-8 -*-

import mysql.connector

db_config = {
    "database": "mydata",
    "user": "root",
    "password": "123456",
    "host": "127.0.0.1",
    "port": 3306,
}

# 连接数据库获取游标,可以设置返回数据的格式,元组,命令元组,字典等...
connect = mysql.connector.Connect(**db_config)

cursor = connect.cursor(dictionary=True)

# 关闭游标和连接
cursor.close()
connect.close()      

写操作

数据 写入 和 更新 都可以使用

execute

executemany

删除就使用

execute

写操作都需要

commit

才会生效

# 插入元组数据
insert_tuple_sql = "insert into student(name, age) values(%s, %s)"
data = ("Tom", 23)
cursor.execute(insert_tuple_sql, data)
connect.commit()
print(cursor.lastrowid)   # 一般插入一条时使用,获取插入id

# 插入多条元组数据
insert_tuple_sql = "insert into student(name, age) values(%s, %s)"
data = [
    ("Tom", 23),
    ("Jack", 25),
]
cursor.executemany(insert_tuple_sql, data)
connect.commit()


# 插入字典数据
insert_dict_sql = "insert into student(name, age) values(%(name)s, %(age)s)"
data = {
    "name": "Tom",
    "age": 25
}

cursor.execute(insert_dict_sql, data)
connect.commit()

# 插入多条字典数据
insert_dict_sql = "insert into student(name, age) values(%(name)s, %(age)s)"
data = [
    {
        "name": "Tom",
        "age": 26
    },
    {
        "name": "Jack",
        "age": 27
    }
]

cursor.executemany(insert_dict_sql, data)
connect.commit()
      

读操作

cursor.execute("select * from student where name=%s limit 3", ("Tom",))
rows = cursor.fetchall()
print(rows)

# 因为开始设置的返回数据格式是字典 dictionary ,所以直接返回字典数据
# [
#  {'id': 1, 'name': 'Tom', 'age': 23},
#  {'id': 2, 'name': 'Tom', 'age': 23},
#  {'id': 3, 'name': 'Tom', 'age': 25}
#]

# 获取一些元数据信息
print(cursor.column_names)  # ('id', 'name', 'age')

print(cursor.description)
# [
#  ('id', 3, None, None, None, None, 0, 16899),
#  ('name', 253, None, None, None, None, 1, 0),
#  ('age', 3, None, None, None, None, 1, 0)
#]

print(cursor.rowcount)  # 3

print(cursor.statement)
# select * from student where name='Tom' limit 3

print(cursor.with_rows)
# True