本文章介绍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'