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-...
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
- 1
代码示例
连接管理
# -*- 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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
写操作
数据 写入 和 更新 都可以使用 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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
读操作
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/93890364
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)