python通过pymysql来操作mysql数据库

首先下载pymysql,用来操作mysql数据库 pip install pymysql

(如果用的是Anaconda也可以使用 conda install pymysql 下载)

导入pymysql并测试连接

import pymysql
db=pymysql.connect('localhost','root','a','ibike')
cursor=db.cursor()
cursor

输出结果:
在这里插入图片描述

建表(如存在,删除)

# 如果数据表已经存在使用 execute() 方法来删除表
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)
db.close()

插入数据

db=pymysql.connect('localhost','root','a','ibike')
cursor=db.cursor()
sql="""INSERT INTO EMPLOYEE (FIRST_NAME,LAST_NAME,AGE,SEX,INCOME) 
        VALUES ('MAC','MOHAN','20','M','1999')"""
try:
    #执行sql语句
    cursor.execute(sql)
    db.commit()
    print('添加成功')
except Exception as e:
    db.rollback()
    print('添加失败',e)
db.close()

用占位符 插入数据

# 用占位符 插入数据
pymysql.paramstyle='format'
db=pymysql.connect('localhost','root','a','ibike')
cursor=db.cursor()
sql="""INSERT INTO EMPLOYEE (FIRST_NAME,LAST_NAME,AGE,SEX,INCOME) 
        VALUES ('%s','%s','%s','%s','%s')"""
try:
    #执行sql语句
    cursor.execute(sql % ('MAC1','MOHAN1','20','M','1999'))
    db.commit()
    print('添加成功')
except Exception as e:
    db.rollback()
    print('添加失败',e)
db.close()

update 更新数据

pymysql.paramstyle='format'
db=pymysql.connect('localhost','root','a','ibike')
cursor=db.cursor()
sql="""UPDATE EMPLOYEE SET AGE=AGE+1 WHERE SEX='%s'"""%('M')
try:
    #执行sql语句
    cursor.execute(sql)
    db.commit()
    print('更新成功')
except Exception as e:
    db.rollback()
    print('更新失败',e)
db.close()

删除数据

pymysql.paramstyle='format'
db=pymysql.connect('localhost','root','a','ibike')
cursor=db.cursor()
sql="DELETE FROM EMPLOYEE WHERE AGE < %s"
try:
    #执行sql语句
    cursor.execute(sql,21)
    db.commit()
    print('删除成功')
except Exception as e:
    db.rollback()
    print('删除失败',e)
db.close()

查询所有数据并打印

方法1:

pymysql.paramstyle='format'
db=pymysql.connect('localhost','root','a','ibike')
cursor=db.cursor()
sql="select * from employee where income>'%s' " %(1000)
try:
    cursor.execute(sql)
    result=cursor.fetchall()
    for row in result:
        fname=row[0]
        lname=row[1]
        age=row[2]
        sex=row[3]
        income=row[4]
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d"  %(fname,lname,age,sex,income)  )
        
except Exception as e:
    print("Error:ubable to fetch data",e)
db.close()

方法2:

# 定义上下文管理器,连接后自动关闭连接
class mysql: #定义一个生命周期控制
    def __init__(self,host='localhost',port=3306,user='root',passwd='a',db='ibike',charset='utf8'):
        self.conn=pymysql.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset=charset)
    def __enter__(self):
        self.cursor=self.conn.cursor()
        return self.cursor
    def __exit__(self,exceptionType,exceptionVal,trace):
        self.conn.commit()
        self.cursor.close()
        self.conn.close()
        
with mysql() as cursor:
    cursor.execute(sql)
    result=cursor.fetchall()
    for row in result:
        fname=row[0]
        lname=row[1]
        age=row[2]
        sex=row[3]
        income=row[4]
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d"  %(fname,lname,age,sex,income)  )
        

方法3:

# 定义上下文管理器,连接后自动关闭连接
import contextlib

@contextlib.contextmanager
def mysql(host='localhost',port=3306,user='root',passwd='a',db='ibike',charset='utf8') :
    conn=pymysql.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset=charset)
    cursor=conn.cursor()
    try:
        yield cursor
    finally:
        conn.commit()
        cursor.close()
        conn.close()
        
with mysql() as cursor:
    cursor.execute(sql)
    result=cursor.fetchall()
    for row in result:
        fname=row[0]
        lname=row[1]
        age=row[2]
        sex=row[3]
        income=row[4]
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d"  %(fname,lname,age,sex,income)  )

ps:

with…as,就是个python控制流语句,像 if ,while一样。
with…as语句是简化版的try except finally语句。
先执行class里面的__enter__函数,它的返回值会赋给as后面的variable,想让它返回什么就返回什么,只要你知道怎么处理就可以了,如果不写as variable,返回值会被忽略

@contextlib.contextmanager
在方法中 yieid之前的相当于__enter__函数 , yieid之后相当于类的__exit__函数
也可以通过with…as… 来操作

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值