本文章介绍Python对mysql的连接以及一些基本操作
import pymysql
# 连接数据库
connect = pymysql.connect(host='localhost', port='3306',user='root', password='root', database = 'test')
# 获取游标
cursor = connect.cursor()
# 删除库
# dropDatabase = 'drop database if exists test '
# cursor.execute(dropDatabase)
# 创建新的库
# createDatabase = 'create database test'
# cursor.execute(createDatabase)
# 删除表
dropTable = 'drop Table if EXISTS testTable'
cursor.execute(dropTable)
# 创建新的表
createTable = 'create Table testTable(id INT auto_increment PRIMARY KEY,NUMBER int NOT NULL )'
cursor.execute(createTable)
# 插入数据
try:
insertData = 'insert into testTable values (0,1), (0,2), (0,3), (0,4), (0,5)'
cursor.execute(insertData)
connect.commit()
except:
connect.rollback()
# 删除数据
try:
deleteData = 'delete from testTable where NUMBER > 5'
cursor.execute(delete

本文档详细介绍了如何使用Python的pymysql模块连接到MySQL数据库,进行创建、删除数据库与表,以及插入、删除、修改和查询数据的操作。在执行SQL语句时,通过游标cursor进行操作,并采用try-except结合rollback来防止数据误操作。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



