用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()
相关推荐
这儿有一堆花31 分钟前
python视觉开发
开发语言·python
普通网友31 分钟前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
桦01 小时前
【MySQL】视图
数据库·mysql
瀚高PG实验室1 小时前
安全版普通用户获取系统对象的访问权限
数据库·安全·瀚高数据库
yy7634966681 小时前
Teigha删除操作完全指南 | 安全彻底清理DWG文件,避免数据灾难!
数据库·安全
RPA机器人就选八爪鱼2 小时前
RPA财务机器人:重塑财务效率,数字化转型的核心利器
大数据·数据库·人工智能·机器人·rpa
小猪绝不放弃.2 小时前
数据库视图的作用分析
数据库
k***12172 小时前
从 SQL 语句到数据库操作
数据库·sql·oracle
a***11352 小时前
使用Django Rest Framework构建API
数据库·django·sqlite
w***4812 小时前
Python中的简单爬虫
爬虫·python·信息可视化