栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python连接数据库

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python连接数据库

  • 操作流程源代码
import pymysql

try:
    # 连接数据库
    db = pymysql.connect(
        host="localhost",  # 主机地址
        user="root",   # 数据库用户名
        password="lubi5824",  # 用户密码
        database="dbtest"  # 连接的数据库名
    )
    print("数据库连接成功!")
    # 创建游标
    cur = db.cursor()

    # 创建表
    sql = 'create table student(Name char(20) not null, Email char(20), Age int)'
    cur.execute(sql)
    print("表格创建成功!")

    # 插入数据
    sql = 'insert into student(Name, Email, Age) value (%s, %s, %s)'
    value = ('Mike', '123@163.com', 20)
    cur.execute(sql, value)
    db.commit()  # 提交数据库
    print("数据插入成功!")

    # 查询数据
    sql = 'select * from student'
    cur.execute(sql)
    results = cur.fetchall()  # 获取数据,得到一个二维表
    for row in results:
        name = row[0]
        email = row[1]
        age = row[2]
        print('Name:%s, Email:%s, Age:%s' % (name, email, age))

    # 更新数据
    sql = "update student set Name=%s where name=%s"
    value = ('John', 'Mike')
    cur.execute(sql, value)
    db.commit()  # 提交数据库
    print("数据更新成功!")

    # 删除数据
    sql = 'delete from student where Name=%s'
    value = ('John')
    cur.execute(sql, value)
    db.commit()  # 提交数据库
    print("数据删除成功!")

    # 删除数据表
    sql = 'drop table if exists Student'
    cur.execute(sql)
    print("表格删除成功!")
except pymysql.Error as e:
    print("操作失败!" + str(e))
    db.rollback()   # 回滚事物

db.close()  # 关闭数据库
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/982175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号