人工智能系列6 使用 Python 操作 MySQL

使用 pymysql 库操作 MySQL

安装 pymysql。

pip install pymysql

创建 mysql.json(数据源配置文件)。

{
  "host": "localhost",
  "user": "root",
  "password": "root",
  "database": "testdb",
  "charset": "utf8"
}

读取配置文件,连接数据库,对数据库做增删改查。

import json
import traceback

import pymysql

# 读取数据源配置文件
with open('mysql.json', encoding='utf-8') as db_json:
    con_config = json.load(db_json)

db = pymysql.connect(
    host=con_config["host"],
    user=con_config["user"],
    password=con_config["password"],
    database=con_config["database"],
    charset=con_config["charset"]
)

cursor = db.cursor()

try:
    # 参数统一用 %s 占位
    sql = 'UPDATE t2 SET t_id = %s WHERE id = %s'
    var = ('新值', 1)
    cursor.execute(sql, var)

    # 需要提交才能生效
    db.commit()
    print('update success,row: %s' % cursor.rowcount)

    sql = 'SELECT * FROM t2 WHERE id = %s'
    
    # 参数使用 tuple 包装. 当 tuple 只有一个值时, 需要加上“,” , 否则“()”会被认为是优先级运算符
    var = (1,)
    
    # 执行sql
    cursor.execute(sql, var)
    
    # 获取所有记录
    data = cursor.fetchall()
    
    for item in data:
        id = item[0]
        t_id = item[1]
        print('id=%s, t_id=%s' % (id, t_id))
        
except Exception as e:
    traceback.print_exc()
finally:
    cursor.close()
    db.close()

打印结果如下:

update success,row: 1
id=1, t_id=新值

使用 ORM 框架操作 MySQL

Python 中比较有名的 ORM 框架是 SQLAlchemy ,以下是操作示例。

from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建对象的基类
Base = declarative_base()


# 定义类
class Student(Base):
    # 表的名字
    __tablename__ = 'test_iu'

    # 表的结构
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(20))
    age = Column(Integer)


# 初始化数据库连接, MySQL 8.0 以上需要添加 auth_plugin 参数
engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/test5?auth_plugin=mysql_native_password')

DBSession = sessionmaker(bind=engine)

# 获取 session 对象
session = DBSession()

# 1.新增多条记录
for s in ('s4', 's5'):
    # 创建对象,添加到 session
    session.add(Student(name=s, age=0))
session.commit()

# 2.查询记录,调用all()则查询所有. 这里 name 的字符串比较要使用“==”
stu = session.query(Student).filter(Student.name == 's1').one()
print('name: ', stu.name)

# 3.修改记录. 先查询出要更改的记录, 然后修改对象, 修改完直接 commit 即可
stu = session.query(Student).filter(Student.name == 's1').one()
stu.name = 'new_s1'
session.commit()

# 4. 删除记录. 先查询出要删除的记录,然后调用 delete(), 再 commit 即可
stu = session.query(Student).filter(Student.name == 'new_s1').all()
for s in stu:
    session.delete(s)
session.commit()

# 关闭 session
session.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jason说编程

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

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

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

打赏作者

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

抵扣说明:

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

余额充值