用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()
相关推荐
AntBlack34 分钟前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉
凪卄12131 小时前
图像预处理 二
人工智能·python·深度学习·计算机视觉·pycharm
巫婆理发2221 小时前
强化学习(第三课第三周)
python·机器学习·深度神经网络
seasonsyy1 小时前
1.安装anaconda详细步骤(含安装截图)
python·深度学习·环境配置
水瓶_bxt1 小时前
Centos安装HAProxy搭建Mysql高可用集群负载均衡
mysql·centos·负载均衡
♡喜欢做梦1 小时前
【MySQL】深入浅出事务:保证数据一致性的核心武器
数据库·mysql
遇见你的雩风1 小时前
MySQL的认识与基本操作
数据库·mysql
半新半旧1 小时前
python 整合使用 Redis
redis·python·bootstrap
dblens 数据库管理和开发工具1 小时前
MySQL新增字段DDL:锁表全解析、避坑指南与实战案例
数据库·mysql·dblens·dblens mysql·数据库连接管理
weixin_419658311 小时前
MySQL的基础操作
数据库·mysql