Python学习 Day48 Python与MySQL的交互操作 14

Python与MySQL的交互操作

一、mysql-connector

(一)安装

  • 安装第三方库:mysql-connector
    在这里插入图片描述

(二)常用操作

  • 1.插入数据 insert
  • 2.查询数据 select
  • 3.更新数据 update
  • 4.创建数据库连接
    connect(host,user,password,database)
import mysql.connector

#创建连接对象
conn = mysql.connector.connect(host='localhost',user='root',passwd='123456',database='test',auth_plugin='mysql_native_password')
#print(conn)
mycursor = conn.cursor()

#编写mysql语句
sql='insert into dept (deptno,dname,loc) values(%s,%s,%s)'
val = (50,'开发部','北京')

#执行SQL语句
mycursor.execute(sql,val)

#提交
conn.commit()
print(mycursor.rowcount,'记录插入成功')

mysql-connector与Python的兼容性不好易报错,所以接下来更换pymysql模块
在这里插入图片描述


二、pymysql

import pymysql

# 打开数据库连接
db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 插入语句
sql = """INSERT INTO dept (deptno,dname,loc) 
         values(50,'开发部','北京')"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()

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

在这里插入图片描述


三、批量插入数据

步骤

  • 1.获取连接对象
  • 2.获取cursor对象
  • 3.编写SQL语句
  • 4.使用列表赋值
  • 5.调用executemany()执行SQL语句
  • 6.提交事务
import pymysql

# 打开数据库连接
db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 插入语句
sql='insert into dept (deptno,dname,loc) values (%s,%s,%s)'
vals = [
    (60,'财务部','上海'),
    (70,'测试部','长春'),
    (80,'市场部','深圳')
]

try:
    # 执行sql语句
    cursor.executemany(sql,vals)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()

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

在这里插入图片描述


四、更新数据与删除数据

步骤

  • 1.获取连接对象
  • 2.获取cursor对象
  • 3.编写SQL语句
  • 4.执行SQL语句
  • 5.提交事务

更新数据

import pymysql

# 打开数据库连接
db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

#编写SQL语句
sql = "update dept set dname = 'Python部门' where deptno = 50"

#执行SQL语句
cursor.execute(sql)

#提交事务
db.commit()
print(cursor.rowcount,'修改成功')
1 修改成功

Process finished with exit code 0

在这里插入图片描述


删除数据

#编写SQL语句
#sql = "update dept set dname = 'Python部门' where deptno = 50" 修改操作
sql = "delete from dept where deptno = 80" #删除操作
1 删除成功

Process finished with exit code 0

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ShengXIABai/article/details/116205635
今日推荐