import pymysql
# # 连接数据库
# db = pymysql.connect(host='localhost', user='root', password='0216', port=3306)
# cursor = db.cursor() # 获得MySQL的操作游标,利用游标来执行SQL语句
# # 创建数据库
# cursor.execute('CREATE DATABASE if NOT EXISTS spiders DEFAULT CHARACTER SET UTF8MB4')
# db.close()
# 创建数据表
db = pymysql.connect(host='localhost', user='root', password='0216', port=3306, db='spiders')
cursor = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'
cursor.execute(sql)
# 插入数据
data = {
'id': '20120001',
'name': 'Bob',
'age': 20
}
table = 'students'
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
# INSERT INTO students(id, name, age) VALUES (%s, %s, %s)
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
try:
if cursor.execute(sql, tuple(data.values())):
print('Successful')
db.commit()
except:
print('Failed')
db.rollback()
db.close()
''' 数据插入、更新、删除操作,都需要调用commit()才能生效。
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
'''
# 更新数据
sql = 'UPDATE students SET age = %s WHERE name = %s'
try:
cursor.execute(sql, (25, 'Bob'))
db.commit()
except:
db.rollback()
db.close()
# 删除数据
table = 'students'
condition = 'age > 20'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table=table, condition=condition)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
# 查询数据
sql = 'SELECT * FROM students WHERE age >= 20'
# fetchone() 获取结果的第一条数据
# fetchall() 得到结果的所有数据
try:
cursor.execute(sql)
print('Count:', cursor.rowcount)
row = cursor.fetchone()
while row:
print('Row:', row)
row = cursor.fetchone()
except:
print('Error')