当前位置:首页 > python > 正文内容

python—pymysql的增删改查操作实例展示

zhangsir3年前 (2022-12-21)python226

Python使用pymysql连接数据库

1.导包

import pymysql


2.连接数据库

connection = pymysql.connect(
    host='',  # 数据库地址
    port=3306, #端口
    user='',  # 数据库用户名
    password='',  # 数据库密码
    db='',  # 数据库名称
    # charset = 'utf8 -- UTF-8 Unicode'
)


3.创建游标

cursor = connection.cursor()


4.数据操作

查询

            #SQL语句
        sql = 'select * from user'
        #execute执行操作
        cursor.execute(sql)
        result = cursor.fetchall()
        print(type(result),cursor.rowcount)
        print(result)



fetchall 查询时获取结果集中的所有行,一行构成一个元组,然后再将这些元组返回(即嵌套元组)。

ferchone 查询时获取结果集的第一行数据,返回一个元组,该元组元素即为第一行数据,如果没有则为null(注:在python中使用应为None)

execute 为单条数据插入

executemany 批量数据插入

cursor.rowcount 用来记录操作次数


插入(批量插入)

            #插入SQL语句
        sql = 'insert into user(username,sex,password,pid,tel) values (%s,%s,%s,%s,%s)'
        #插入数据
        data = [
            ('test1', '男', '123456', 3, '110'),
            ('test2', '女', '123456', 2, '120'),
        ]
        #拼接并执行SQL语句
        cursor.executemany(sql,data)
        #涉及写操作要提交
        connection.commit()
        print(cursor.rowcount)


不管数据库中的数据类型是什么,在sql语句中统一使用字符串类型%s connection.commit() 涉及写操作要提交

修改

            #修改SQL语句
        sql = 'update user set tel="12345622" where id="64"'
        #执行SQL语句
        cursor.execute(sql)
        connection.commit()
        print(cursor.rowcount)


删除

            #删除SQL语句
        sql = 'delete from user where id = 64'
        cursor.execute(sql)
        connection.commit()
        print(cursor.rowcount)


关闭

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


zhangsir版权c2防采集https://mianka.xyz

扫描二维码推送至手机访问。

版权声明:本文由zhangsir or zhangmaam发布,如需转载请注明出处。

本文链接:https://mianka.xyz/post/85.html

标签: pythonpymysql
分享给朋友:

“python—pymysql的增删改查操作实例展示” 的相关文章

如何向python 列表中添加元素

Python添加元素有三种方法:append、extend、insertappend:向列表添加元素,添加到尾部实例:list=[“my”,“name”,“is”,“mark”,“age”,18] print(“添加前:”,list) list.append(“test”) print(“添加...

django框架的安装和创建第一个项目

安装Djangopip install -i https://pypi.douban.com/simple django创建项目django-admin startproject 项目名称例如 django-admin startproje...

python 写入文件

一、读写txt文件1、打开txt文件Note=open('x.txt',mode='w',encoding='utf-8')函数=open(x.扩展名,mode=模式)模式种类:w      ...

python+selenium元素定位的8种方法

定位元素,selenium提供了8中元素定位方法:(1)find_element_by_id() :html规定,id在html中必须是唯一的,有点类似于身份证号(2)find_element_by_name() :html规定,name用来指定元素的名称,有点类似于人名(3)find_elemen...

pip安装三方库 国内的一些镜像站点推荐

pip 国内的一些镜像站点推荐镜像套路:使用cmd;输入命令pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名 即可开始安装。清华:https://pypi.tuna.tsinghua.edu.cn/simple 阿里云:http...

权大师商标查询api

''' data:2022-10-15 autor:zhangsir 权大师商标查询api ''' import requests import json import time import h...