python3 mysql增删改查

示例表 test

 

插入操作

import pymysql                              #导入pymysql

db=pymysql.connect(host="localhost",
                   user="root",
                   password="root",
                   db="test",
                   port=3306
                   )                        #创建数据库对象

cur = db.cursor()

sql = "INSERT INTO `test` (`id`, `name`, `password`) VALUES ('3', 'test1', 'test1')"

try:
  cur.execute(sql)                     #执行sql
  db.commit()                          #提交

except Exception as e:
  db.rollback()                       #异常回滚

finally:
  db.close() 

查询操作

import pymysql                              #导入pymysql

db=pymysql.connect(host="localhost",
                   user="root",
                   password="root",
                   db="test",
                   port=3306
                   )                        #创建数据库对象

cur = db.cursor()                           #获取游标

sql = "select * from test"

try:
    cur.execute(sql)
    res = cur.fetchall()                    #查询多条数据,使用循环进行输出
    #res = cur.fetchone()                   #查询一条 直接输出
    print("id","name","password")
    #print(res)
    for row in res:
        id = row[0]
        name = row[1]
        password = row[2]
        print(id,name,password)

except Exception as e:
    raise e

finally:
    db.close()

 

更新操作

import pymysql                              #导入pymysql

db=pymysql.connect(host="localhost",
                   user="root",
                   password="root",
                   db="test",
                   port=3306
                   )                        #创建数据库对象

cur = db.cursor()   

sql = "UPDATE test set name = '%s',password = '%s' where id = %d"

try:
  cur.execute(sql% ("ddd","ddd",2))
  db.commit()

except Exception as e:
  db.rollback()

finally:
  db.close()

删除操作

import pymysql                              #导入pymysql

db=pymysql.connect(host="localhost",
                   user="root",
                   password="root",
                   db="test",
                   port=3306
                   )                        #创建数据库对象

cur = db.cursor()     

sql = "DELETE from test where id = %d"

try:
  cur.execute(sql% (2))
  db.commit()

except Exception as e:
  db.rollback()

finally:
  db.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值