0
点赞
收藏
分享

微信扫一扫

python操作mysql数据库

颜娘娘的碎碎念 2022-02-08 阅读 59

在python大数据中,我们可以用数据库来存储数据,我这篇笔记是介绍python用pymysql连接mysql数据库。

相关命令:

win + r =》 cmd # ------------ 进入命令提示符

net start mysql # ------------ 开启数据库服务

net stop mysql # ------------ 关闭数据库服务

pip install pymysql # ----------- 安装pymysql模块

pip list # ------------ 查看已安装模块

student表数据:

数据查询语言(DQL) 

import pymysql

# 打开数据库连接
db = pymysql.connect(host="127.0.0.1", user="root",
                     password="xfr2001", db="test", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
# 1.查询操作
sql1 = "SELECT * FROM student;"
try:
    cur.execute(sql1)  # 执行sql语句

    results = cur.fetchall()  # 获取查询的所有记录
    print('执行sql成功:',sql1)
    print('查询结果:')
    print("id\t\t\t", "name\t\t\t", "gender")
    # 遍历结果
    for row in results:
        id = row[0]
        name = row[2]
        gender = row[3]
        print(id, "\t\t\t", name, "\t\t\t", gender)
except Exception as e:
    raise e
finally:
    db.close()  # 关闭连接

运行结果: 

数据操纵语言(DML)

import pymysql

# 打开数据库连接
db = pymysql.connect(host="127.0.0.1", user="root",
                     password="xfr2001", db="test", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql2 = """INSERT INTO student(
c_id,
NAME,
gender,
age, 
heigth
) VALUES(1,'小明','boy',19,165)"""

try:
    cur.execute(sql2)
    # 提交
    db.commit()
    print('sql执行成功:',sql2)
except Exception as e:
    # 错误回滚
    db.rollback()
finally:
    db.close()

运行结果:

数据库中的表: 

 打卡37天,对python大数据感兴趣的朋友欢迎一起讨论,交流,请多指教!

举报

相关推荐

0 条评论