python3与MySQL交互

一 、简述

python3 与MySQL 进行交互编程需要安装 pymysql 库,故首先使用如下命令安装pymysql 。

pip install PyMySQL

那什么是pymysql呢?

  • PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库。
  • 如果安装过程出现 "ImportError: No module named setuptools"的错误提示,意思是你没有安装setuptools,你可以访问这里写链接内容 找到各个系统的安装方法。
  • 然后确保你的设备上面满足如下条件:
    • 创建了数据库 TESTDB.
    • 在TESTDB数据库中您已经创建了表 EMPLOYEE
    • EMPLOYEE表字段为 FirstName, LastName, Age, Sex 和 Income。
    • 连接数据库TESTDB使用的用户名为 “root” ,密码为 “123”(这是我的数据库密码,你的需要改成相应的), Mysql数据库用户授权请使用Grant命令。
  • 如果你对Mysql数据库相关不太熟悉,你可以访问我的这篇文章Mysql教程,熟悉后在进行相关的操作。

二、demo 实战

注意:由于可能因为操作过程中会发生各种错误,于是,这里将相关错误放置在前面,以示提醒。
Error

1 、数据库连接

#!/usr/bin/python3 

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","123","TESTDB")

# 使用 cursor() 方法创建一个游标对象 cursor 
cursor = db.cursor()

# 使用 execute() 方法执行SQL 查询
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取单条数据
data = cursor.fetchone()

print ("\n Database version : %s \n"% data)

# 关闭数据库连接
db.close()

输出结果为: Database version : 5.7.20-0ubuntu0.16.04.1

2 、创建数据库表

#!/usr/bin/pyhton3 

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","123","TESTDB")

# 使用 cursor() 方法创建一个游标对象 cursor 
cursor = db.cursor()

# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("drop table if exists EMPLOYEE")

# 使用预处理语句创建表
sql = """create table EMPLOYEE (
         FirstName char(20) not null,
         LastName char(20),
         Age int,
         Sex char(1),
         Income float )  """
cursor.execute(sql)
print ("\n creat table successd ! \n")

# 关闭数据库连接
db.close()

3 、插入操作

#!/usr/bin/python3 

import pymysql

db = pymysql.connect("localhost","root","123","TESTDB")

cursor = db.cursor()

# sql 插入语句
sql = """insert into EMPLOYEE(FirstName,
         LastName,Age,Sex,Income) 
         values('Mac','Mohan',20,'M',2000);"""

try:
    # 执行 sql 语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
    print ('提交完毕')
except:
    # 如果发生错误则进行回滚
    db.rollback()
        print ('\n Some Error happend ! \n')

# 关闭数据库连接
db.close()

4 、查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

  1. fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  2. fetchall(): 接收全部的返回结果行. rowcount:
  3. 这是一个只读属性,并返回执行execute()方法后影响的行数。
#!/usr/bin/python3 

import pymysql

db = pymysql.connect("localhost",'root','123','TESTDB')

cursor = db.cursor()

sql = "select * from EMPLOYEE \
       where Income > %d" % (1000)

try:
    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 ("\n fname =%s,lname =%s,age = %d, sex=%s,income=%d \n "%(fname,lname,age,sex,income))

except:
    print ("Error: unable to fetch data")

# 关闭数据库连接
db.close()

5 、更新操作

!/usr/bin/python3 

import pymysql

db = pymysql.connect('localhost','root','123','TESTDB')

cursor = db.cursor()

# SQL 更新语句
sql = "update EMPLOYEE set Age = Age + 1 where sex = '%c'"%('M')

try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close()

6 、删除操作

#!/usr/bin/python3 

import pymysql

db = pymysql.connect('localhost','root','123','TESTDB')

cursor = db.cursor()

sql = "delete from EMPLOYEE where Age > '%d' "%(20)

try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
    print ('发生错误,回滚中!')

db.close()
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smilejiasmile

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值