用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()
相关推荐
二哈喇子!23 分钟前
MySQL数据库概述
mysql
二哈喇子!4 小时前
MySQL数据更新操作
数据库·sql
二哈喇子!4 小时前
MySQL命令行导入数据库
数据库·sql·mysql·vs code
心动啊1215 小时前
SQLAlchemy 的使用
数据库
jaray5 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
Psycho_MrZhang5 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
web3.08889995 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python
少云清5 小时前
【性能测试】15_JMeter _JMeter插件安装使用
开发语言·python·jmeter
光羽隹衡6 小时前
机器学习——TF-IDF实战(红楼梦数据处理)
python·tf-idf
曾经的三心草6 小时前
redis-2-数据结构内部编码-单线程-String命令
数据结构·数据库·redis