SQL基础教程 Chapter 9 (python edithon)

本文详细介绍如何使用Python操作MySQL数据库,包括数据库的连接、创建表、插入数据、查询、更新及删除操作,适合初学者和进阶者学习。

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值