typora-copy-images-to: SQL basic
SQL基础教程 Chapter 9
说明:
- 原本第九章是使用JAVA连接操作数据库,本人习惯于操作MySQL,因此此章节更改为Python 操作MySQL数据库
Python 操作 MySQL
- Python的标准数据接口为 Python DB-API,支持众多的数据库
- 不同的数据库需要下载不同的DB API模块
Python DB-API的使用流程:
-
引入API模块
-
获取与数据库的连接
-
执行SQL语句和存储过程
-
关闭数据库的连接
-
数据库的连接
import pymysql
# 打开数据库的连接
db = pymysql.connect("localhost","root","password","testdb")
# 创建一个游标对象
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
#使用fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
- 数据库表的创建
# 创建数据库表
# 打开数据库的连接
db = pymysql.connect("localhost","root","password","testdb")
# 创建一个游标对象
cursor = db.cursor()
cursor.execute("drop table if exists employee")
# 使用预处理语句创建表
sql = """Create table employee(
first_name char(20) not null,
last_name char(20),
age int,
sex char(1),
income float)"""
cursor.execute(sql)
- 数据库插入操作
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","password","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
- 数据库查询操作
# 查询employee表中salary(工资)字段大于1000的所有数据
sql_select = "select * from employee \
where income > 1000 "
try:
cursor.execute(sql_select)
results = cursor.fetchall()
print(results)
except:
print("error")
- 标准的数据库查询操作
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","password","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %s" % (1000)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \(fname, lname, age, sex, income ))
except:
print ("Error: unable to fetch data")
- 数据库更新操作
import pymysql
db = pymysql.connect("localhost","root","password","testdb" )
sql_update = "update employee set age = age + 1 \
where sex = 'm'"
sql_select_new = "select * from employee"
try:
cursor.execute(sql_update)
db.commit()
cursor.execute(sql_select_new)
results = cursor.fetchall()
print(results)
except:db.rollback()
- 删除操作
# 打开连接
# 使用游标
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
# 发生错误时回滚
db.rollback()