Python通过pymysql连接数据库并进行增删改查

1. 前言

 哈喽,大家好,我是小K,今天咋们分享的内容是:Python中如何通过pymysql模块连接数据库 

相信大家都已经学过Mysql啦,对基础的增删改查都已经了如指掌了。

但是,你可能还不会Python如何连接数据库并进行增删改查 ,那么本篇文章带你学会如何通过Python连接数据库 

2. 准备

Python版本:3.8

pymysql版本:1.0.2

先进行安装pymysql

pip install pymysql

如果觉得慢的话,可以加上国内的源:

pip install -i https://pypi.doubanio.com/simple pymysql==1.0.2

 3. 建立连接

 这就是基本的连接代码:

import pymysql


def get_connection():
    conn = pymysql.connect(
        host='localhost',
        user='root',
        password='5201314',
        database='java-test',
        charset='utf8'
    )
    cursor = conn.cursor()  # 获取游标

    cursor.close()  # 关闭游标
    conn.close()   # 关闭连接


if __name__ == '__main__':
    get_connection()

 现在,我们来看每一个参数:

host: 主机地址(localhost代表本地 , 127.0.0.1也代表本地)

user: 用户名

password: 密码

database: 数据库名

charset: 字符集(这里需要注意一下,在mysql中是utf8 , 而不是utf-8)

这是建立sql游标cursor

游标(Cursor)是用来执行 SQL 语句并处理查询结果的对象。它提供了一种在 Python 中与数据库进行交互的方式,允许你执行 SQL 查询、获取查询结果以及处理结果集。

ok, 现在我们来测试,是否连接成功

4. 测试连接成功

import pymysql
def get_connection():
    try:
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='52013144',
            database='java-test',
            charset='utf8'
        )
        cursor = conn.cursor()  # 获取
        # 游标
        # 执行 SQL 查询
        cursor.execute('SELECT VERSION()')
        # 获取查询结果
        db_version = cursor.fetchone()
        print(f'Database version: {db_version[0]}')

        cursor.close()  # 关闭游标
        conn.close()   # 关闭连接
    except pymysql.MySQLError as e:
        print(e)


if __name__ == '__main__':
    get_connection()

 进行测试,查看当前数据库版本

先来错误的密码看看:

再来正确的:

5. 增删改查

先来创建一张表,通过sql语句:

这是在mysql中创建的语句:

create table info(
	id int primary key auto_increment,
	user varchar(10) not null,
    pwd varchar(10)
);

5.1 增

5.1.1 方法1

# 链接数据库
import pymysql
def get_connection():
    try:
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='5201314',
            database='java-test',
            charset='utf8'
        )
        cursor = conn.cursor()  # 获取
        # 游标
        # 执行 SQL 查询
        cursor.execute('SELECT VERSION()')
        # 获取查询结果
        db_version = cursor.fetchone()
        print(f'Database version: {db_version[0]}')

        cursor.execute('insert into info (user,pwd) values ("jiaoxingk", "12dd");')
        conn.commit()

        cursor.close()  # 关闭游标
        conn.close()   # 关闭连接
    except pymysql.MySQLError as e:
        print(e)


if __name__ == '__main__':
    get_connection()

这里需要注意,一定要提交才行

5.1.2 方法2

sql = "insert into info (user,pwd) values ('%s', '%s');" %('kk' , '1231')
cursor.execute(sql)

这种方法,可以动态传入一些变量参数

5.1.3 方法3

sql = "insert into info (user,pwd) values (%s, %s);"
cursor.execute(sql , ('diaomao' , '23123'))
conn.commit()

需要注意:方法2的%s有引号,方法3的%s没有引号 ,这是因为使用这种方式,会把引号当成普通的数据写入到数据库中!

 5.1.4 方法4

这是多条插入的方法:

info_list = [('jiaoxik{}'.format(i), 'ddwass{}'.format(i)) for i in range(5, 101)]
sql = "insert into info (user,pwd) values (%s, %s);"
cursor.executemany(sql , info_list)
conn.commit()

 

5.2 删

sql = 'delete from info where user = %s;'
cursor.execute(sql , 'jiaoxingk')
conn.commit()

5.3 改

sql = 'update  info set user = %s where user = %s;'
cursor.execute(sql , ('jiaoxingk','kk'))

5.4 查

cursor = conn.cursor()  # 获取游标

sql = 'select id, user, pwd from info;'
rows = cursor.execute(sql)
print(rows) 

conn.commit()

如果直接打印返回值rows,得到的是所有记录的条数

想要得到记录内容可以使用fetch系列:

fetchone

一条一条取

cursor = conn.cursor()  # 获取游标

sql = 'select id, user, pwd from info;'
cursor.execute(sql)
print(cursor.fetchone())
print(cursor.fetchone())

conn.commit()

fetchmany

默认从开始取指定条数。

cursor = conn.cursor()  # 获取游标

sql = 'select id, user, pwd from info;'
cursor.execute(sql)
print(cursor.fetchmany(3))  # 默认从开始取指定条数

conn.commit()

fetchall

取所有

cursor = conn.cursor()  # 获取游标

sql = 'select id, user, pwd from info;'
cursor.execute(sql)
print(cursor.fetchall())

conn.commit()

控制返回值

如果你每次看打印结果的话,结果都是以元组套元组的形式返回。

cursor = conn.cursor()
cursor.execute('select * from info;')
print(cursor.fetchmany(2))  # ((7, 'jiaoxingk', '1231'), (8, 'jiaoxingk', '1231'))

我们也可以控制返回形式,比如以列表套字典的形式:

from pymysql.cursors import DictCursor
cursor = conn.cursor(cursor=DictCursor)  # 需要在实例化游标对象的时候,传个参数
cursor.execute('select * from info;')
print(cursor.fetchmany(2))  # [{'id': 7, 'user': 'jiaoxingk', 'pwd': '1231'}, {'id': 8, 'user': 'jiaoxingk', 'pwd': '1231'}]
conn.commit()

scroll

先来看相对定位,根据当前的游标位置移动。

cursor = conn.cursor(cursor=DictCursor)

cursor.execute('select * from info;')
print(cursor.fetchone())  # 此时游标在第一行
cursor.scroll(1, 'relative')  # 光标按照相对位置移动一位,此时在2
print(cursor.fetchone())  # 取第3行记录

conn.commit()
cursor.close()
conn.close()

接下来看绝对定位:

cursor = conn.cursor(cursor=DictCursor)

cursor.execute('select * from info;')
print(cursor.fetchone())  # 此时游标在第一行
cursor.scroll(1, 'absolute')  # 光标按照绝对位置移动一位,此时在1
print(cursor.fetchone())  # 取第2行记录

conn.commit()
cursor.close()
conn.close()

6. 最后

好啦,今天的分享就到这里了。

通过pymysql我们能成功在python环境下连接数据库,并进行增删改查

在后续使用时,如果遇到需要在Python代码里保存数据库操作的话,那么这个方法无疑是最佳的。

  • 27
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我可以为您提供一些关于使用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 ``` 希望这能帮助到您。如果您有其他问题,欢迎随时提出。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jiaoxingk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值