用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()
相关推荐
菜鸟小九2 分钟前
redis基础(数据结构)
数据结构·数据库·redis
WXG10116 分钟前
【Flask-8】程序打包
开发语言·python
NullPointer87 分钟前
【剪映小助手源码精讲】第29章 视频生成服务
python·aigc
bkspiderx8 分钟前
libmysqlclient:MySQL 底层客户端库的全面指南
数据库·mysql·mysqlclient·libmysqlclient·mysql 底层客户端库
Arva .8 分钟前
详细描述一条 SQL 在 MySQL 中的执行过程
数据库·sql·mysql
数据库学啊12 分钟前
好用的车联网时序数据库机构有哪些
大数据·数据库·时序数据库
副露のmagic17 分钟前
更弱智的算法学习 day9
python·学习·算法
weixin_4215850117 分钟前
SpatialTransformer库函数分析二
python·keras
Pyeako17 分钟前
python中pandas库的使用(超详细)
开发语言·python·pandas
Data_agent19 分钟前
京东获得京东商品详情API,python请求示例
java·前端·爬虫·python