pymysql数据库之建库建表、增删改查

上次有同学问到,Python的持久化怎么处理。这次就带大家来体验一下,Python访问数据库。

首先要有个数据库

现在的数据库分类很多,以mysql为例。需要到mysql的官网上去下载mysql。
下载路径
下载打开安装包,勾选常见的安装位置等配置以后,设置数据库用户名密码,启动mysql就可以了。
mac上的启动可以沿着一下路径开启: 系统偏好设置------Mysql------开启。如图所示:
在这里插入图片描述
在这里插入图片描述
点击按钮,当状态标志从红色的stopped变成绿色的running,就说明mysql已经启动完成。

然后需要有个Python模块

Python3的数据库模块可以是pymysql。安装可以通过pip安装:
在这里插入图片描述
安装完成后,你的python数据库的底层依赖算是完成了。

愉快的创建数据库、增删改查

创建数据库可以下载图形客户端(mysql workbench或者navicat等等),也可以通过Python代码。
这里我们使用Python代码来处理:

建库建表

建数据库,库名为awesome;建表,表名blogs;共有三列,列名 id,user_id, name

import pymysql

# 建库和建表
con = pymysql.connect(host='localhost', user='root',
                      passwd='123456', charset='utf8')
cur = con.cursor()
# 开始建库
cur.execute("create database awesome character set utf8;")
# 使用库
cur.execute("use awesome;")
# 建表
cur.execute("create table blogs(id char(20),user_id char(20),name char(20),)character set utf8;")

查询操作

查询表,表名blogs

# 1.建立连接,用户root 密码mysql123456 dbname:awesome
db = pymysql.connect("localhost","root","mysql123456","awesome")
# 获取游标
cur = db.cursor()
# sql查询语句 表名blogs
sql = "select * from blogs"
try:
    cur.execute(sql)  # 执行sql语句

    results = cur.fetchall()  # 获取查询的所有记录
    print("id", "user_id", "name")
    # 遍历结果
    for row in results:
        id = row[0]
        user_id = row[1]
        name = row[4]
        print(id, name, user_id)
except Exception as e:
    raise e
finally:
    db.close()  # 关闭连接

插入操作

往表blog里插入一行数据(id,user_id,name) = (“test_id”,‘test_user_id’,‘test_name’)

# 2.插入操作
db = pymysql.connect("localhost","root","mysql12345","awesome")
cur_insert = db.cursor()

# sql插入语句 表名blogs
sql_insert ="""insert into blogs(id,user_id,name) values ("test_id",'test_user_id','test_name')"""

try:
    cur_insert.execute(sql_insert)
    # 提交
    db.commit()
    print('开始数据库插入操作')
except Exception as e:
    db.rollback()
    print('数据库插入操作错误回滚')
finally:
    db.close()

更新操作

更新user_id = “test_user_id” 的行,将其 name 更新为 “update_test_name”

# 3.更新操作
db = pymysql.connect("localhost","root","mysql12345","awesome")
cur_update = db.cursor()

sql_update = "update awesome.blogs set name = '%s' where user_id = '%s'"
try:
    cur_update.execute(sql_update % ("update_test_name", "test_user_id"))
    # 提交
    db.commit()
    print('开始数据库更新操作')
except Exception as e:
    db.rollback()
    print('数据库更新操作错误回滚')
finally:
    db.close()

删除操作

删除 name = “update_test_name” 的行

# 4.删除操作
db = pymysql.connect("localhost","root","mysql12345","awesome")
cur_delete = db.cursor()

sql_delete = "delete from awesome.blogs where name = '%s'"

try:
    cur_delete.execute(sql_delete % ("update_test_name"))  # 像sql语句传递参数
    # 提交
    db.commit()
    print('开始数据库删除操作')
except Exception as e:
    db.rollback()
    print('数据库删除操作错误回滚')
finally:
    db.close()

这里以mysql为例,如果使用mongodb等其他数据库,使用方法也是类似的,大家可以举一反三。
在这里插入图片描述

  • 5
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以为您提供一些关于使用pymysql库进行MySQL数据库增删改查的基本操作。以下是一个简单的示例代码: ```python import pymysql # 连接到数据库 conn = pymysql.connect(host='localhost', port=3306, user='root', password='your_password', db='your_database') # 创建游标对象 cursor = conn.cursor() # 插入数据 sql_insert = "INSERT INTO your_table (name, age, gender) VALUES (%s, %s, %s)" data = ('John', 25, 'male') cursor.execute(sql_insert, data) conn.commit() # 更新数据 sql_update = "UPDATE your_table SET age = %s WHERE name = %s" data = (30, 'John') cursor.execute(sql_update, data) conn.commit() # 删除数据 sql_delete = "DELETE FROM your_table WHERE name = %s" data = ('John',) cursor.execute(sql_delete, data) conn.commit() # 查询数据 sql_select = "SELECT * FROM your_table WHERE name = %s" data = ('John',) cursor.execute(sql_select, data) results = cursor.fetchall() # 打印结果 for row in results: name = row[0] age = row[1] gender = row[2] print(f"name: {name}, age: {age}, gender: {gender}") # 关闭游标和连接 cursor.close() conn.close() ``` 需要注意的是,以上代码中的参数需要根据您自己的数据库配置进行修改,包括数据库地址、端口、用户名、密码、数据库名、数据表名等。同时,您需要安装pymysql库,可以通过以下命令进行安装: ```bash pip install pymysql ``` 希望这能帮助到您。如果您有其他问题,欢迎随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值