用pymysql操作数据库

用pymysql操作数据库随笔

python 复制代码
from pymysql import Connection

con = True
try:
    # 创建数据库连接
    con = Connection(
        host='localhost',
        port=3306,
        user='root',
        password='root',
        database='db_python',  # 设置要连接的数据库名称
        autocommit=True  # 设置自动提交
    )
    # 创建cursor对象
    cursor = con.cursor()
    # 创建一张表
    sql = """
    create table tb_goods(
    id int auto_increment primary key,
    name varchar(20) not null,
    price decimal(11,2) not null
    ) engine=innodb default charset=utf8;
    """
    # 执行这段sql
    cursor.execute(sql)
    print('表创建成功')
    # 向表中插入一些数据
    cursor.execute("insert into tb_goods values (1,'西瓜','10'),(2,'香蕉','5');")
    print('插入成功')
    # 查询这张表中的数据
    cursor.execute("select * from tb_goods;")
    print('查询成功')
    # 将查询出来的数据显示在控制台
    result = cursor.fetchall()
    for row in result:
        print(row)
    # 更新表中的数据
    cursor.execute("update tb_goods set price=15 where id=1")
    print("更新后的数据")
    cursor.execute("select * from tb_goods;")
    result1 = cursor.fetchall()
    for i in result1:
        print(i)
except Exception as e:
    print("异常:", e)
finally:
    if con:
        con.close()
相关推荐
倔强的石头_12 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
SelectDB14 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
jiayou642 天前
KingbaseES 表级与列级加密完全指南
数据库·后端
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络