连接
import pymysql
connection = pymysql.connect(
host='localhost',
user='root',
password='pass_word',
db='db_name',
charset='utf8',
cursorclass=pymsql.cursors.DictCursor
)
方法 |
说明 |
cursor() |
获取游标对象 |
commit() |
提交事务 |
rollback() |
回滚事务 |
close() |
关闭数据库连接 |
获取游标
import pymysql
connection = pymysql.connect(...)
cursor = connection.cursor()
方法 |
说明 |
excute(operation[, parameters]) |
执行单条指令 |
excutemany(operation, seq_of_params) |
批量执行指令(批量更新…) |
fetchone() |
获取查询结果的下一条结果 |
fetchmany(size) |
获取指定数量的结果 |
fetchall() |
获取所有查询结果 |
close() |
关闭当前游标 |
执行指令并提交
增
删
改
通过执行不同的 MySQL 指令实现
更详细的SQL指令,参考之前的这篇文章【点击查看】
import pymysql
connection = pymysql.connect('localhost', 'root',
'pass_word', 'my_db', charset='utf8')
cursor = connection.cursor()
create_table_sql = '''create table mytable
id int(20) not null primary key,
name varchar(20) unicode not null,
gender varchar(8) unicode not null,
)engine=InnoDB default charset=utf8mb4;
'''
insert_one_sql = 'insert into mytable(id, name, gender) values(10010, "Bender", "Male")'
insert_many_sql = "insert into mytable values(%s, %s, %s)"
datas = [[10011, "Leela", "Famale"],
[10012, 'Fry', 'Male']]
cursor.excute(create_table_sql)
cursor.excute(insert_one_sql)
cursor.excutemany(insert_many_sql, datas)
connection.commit()
回滚
- 发生错误时,回滚
import pymysql
try:
connection = pymysql.connect(...)
cursor = conection.cursor()
cursor.excute('insert into mytable values(***,***,***)'
connection.commit()
except:
connection.rollback()
connection.close()
查询
import pymysql
connection = pymysql.connect(...)
cursor = connection.cursor()
select_sql = 'select id,name,gender from mytable where id>10010'
cursor.excute(select_sql)
datas = cursor.fetchall()
for data in datas:
print(f'id: {data["id"]}\t'
f'name: {data["name"]}\t'
f'gender: {data["gender"]}')
connection.close()
关闭