-
创建表
# 通过python连接数据库,创建数据表
db = pymysql.connect("localhost", "root", "123456", "gddx")
# 使用cursor()方法准备游标对象
cursor = db.cursor()
# 使用Execute()方法执行SQL查询
cursor.execute("DROP TABLE IF EXISTS employee")
sql = """CREATE TABLE `employee`(
`id` int(10) NOT NULL AUTO_INCREMENT,
`frist_name` char(20) NOT NULL,
`last_name` char(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`income` float DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
# 创建表
cursor.execute(sql)
print("Created table Successfull.")
# 关闭数据库
db.close()```
-
插入数据
# 通过python连接数据库,创建数据表
db = pymysql.connect("localhost", "root", "123456", "gddx")
# 使用cursor()方法准备游标对象
cursor = db.cursor()
# 写上插入语句
sql = """INSERT INTO employee(frist_name,
last_name, age, sex, income)
VALUES ('chen', 'sanmi', 24, 'W', 8000)"""
# 尝试折行语句
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
print (sql)
print('Yes, Insert Successfull.')
# 关闭数据库
db.close()```
-
动态插入数据
# 通过python连接数据库,创建数据表
db = pymysql.connect("localhost", "root", "123456", "gddx")
# 使用cursor()方法准备游标对象
cursor = db.cursor()
# 写上插入语句
sql = "INSERT INTO employee(frist_name, \
last_name, age, sex, income) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('wu', 'huarou', 25, 'W', 10000)
# 尝试折行语句
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
print(sql)
print('Yes, Insert Successfull.')
# 关闭数据库
db.close()```
-
读取数据
# 通过python连接数据库,创建数据表
db = pymysql.connect("localhost", "root", "123456", "gddx")
# 使用cursor()方法准备游标对象
cursor = db.cursor()
# 按字典返回
# cursor = db.cursor(pymysql.cursors.DictCursor)
# 写上插入语句
sql = "SELECT * FROM employee \
WHERE income >= %d" % (10000)
# 尝试折行语句
try:
cursor.execute(sql)
# 获取每一行数据
results = cursor.fetchall()
for row in results:
print(row)
fname = row[1]
lname = row[2]
age = row[3]
sex = row[4]
income = row[5]
print("name = %s %s,age = %s,sex = %s,income = %s" % \
(fname, lname, age, sex, income))
except:
import traceback
traceback.print_exc()
print ("Error: unable to fetch data")
# 关闭数据库
db.close()```
-
更新数据
# 通过python连接数据库,创建数据表
db = pymysql.connect("localhost", "root", "123456", "gddx")
# 使用cursor()方法准备游标对象
cursor = db.cursor()
sql = "UPDATE EMPLOYEE SET AGE = AGE - 1 \
WHERE SEX = '%c'" % ('M')
# 尝试折行语句
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
# 关闭数据库
db.close()```
-
删除数据
# 通过python连接数据库,创建数据表
db = pymysql.connect("localhost", "root", "123456", "gddx")
# 使用cursor()方法准备游标对象
cursor = db.cursor()
sql = "DELETE FROM EMPLOYEE WHERE AGE = '%d'" % (25)
# 尝试折行语句
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
# 关闭数据库
db.close()```