MySQL数据库-pymysql模块操作数据库

news/2024/8/26 10:56:44

pymysql模块是python操作数据库的一个模块

 

connect()创建数据库链接,参数是连接数据库需要的连接参数
使用方式:
  模块名称.connect()
  参数:
  host=数据库ip
  port=数据库端口
  user=数据库用户名
  passwd=数据库密码
  db=数据库名称

  charset=数据库编码


cursor()创建数据库操作游标,无参
使用方式:
  游标变量.cursor()


execute()操作数据库,参数1 sql语句,参数2 字符串占位符变量
使用方式:
  游标变量.execute()

execute()操作数据库会返回,操作数据库后影响的行数,我们可以以此判断是否操作成功


commit()提交数据到数据库,无参
使用方式:
  创建数据库链接变量.commit()


close()关闭游标
使用方式:
  游标变量.close()


close()关闭数据库
使用方式:
  创建数据库变量.close()

__author__ = 'zjl'
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='mysql123',database="day17",charset="utf8")
cursor=conn.cursor()
# 创建游标

# 执行SQL,并返回收影响行数
v=cursor.execute("select * from class")
print(v)
effect_row = cursor.execute("INSERT INTO shirts(name) VALUES('adc8868')")#添加一条数据
print(effect_row)
# 提交,不然无法保存新建或者修改的数据
conn.commit()

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

execute(sql语句%s,(占位符变量))执行sql语句时的占位符使用

execute()操作一条数据

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='279819', db='cshi')
# 创建游标
cursor = conn.cursor()

# 执行SQL,并返回收影响行数
effect_row = cursor.execute("INSERT INTO shirts(yhm,mim) VALUES(%s,%s)",('adc279819',279819)) #添加一条数据
print(effect_row)   #返回影响行数

# 提交,不然无法保存新建或者修改的数据
conn.commit()

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

查询数据库数据

注意:操作数据库的增、删、改都需要commit()提交数据到数据库,而查询是不需要commit()的

fetchall()获取游标查询数据库里的数据,返回元祖
使用方式:
  游标变量.fetchall()

 

查询数据库内容时更改游标返回字典类型数据【推荐】

返回字典类型将数据库表的列(字段)作为键返回

默认查询数据时游标返回的元祖类型,如果想返回字典类型就需要设置游标

cursor=pymysql.cursors.DictCursor设置游标返回字典类型数据,当做参数写在execute()里,execute(cursor=pymysql.cursors.DictCursor)

#!/usr/bin/python
# -*- coding:utf-8 -*-
import pymysql

# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 受影响的行数
v = cursor.execute('select * from student')
result = cursor.fetchall()
print(result)

cursor.close()
conn.close()

移动游标里数据指针获取对应数据

scroll(1,mode='relative')相对当前位置移动
  使用方式:
  游标变量.scroll(1,mode='relative')
  第一个参数正数相对当前位置向下移动数值对应指针,第一个负数相对当前位置向上移动数值对应指针

scroll(2,mode='absolute')相对绝对位置移动
  使用方式:
  游标变量.scroll(2,mode='absolute')
  将指针位置移动到第一个参数数值对应指针

相对当前位置移动获取数据mode='relative'

 

import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='mysql123',database="day17",charset="utf8")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 受影响的行数
v = cursor.execute('select * from student')
result = cursor.fetchone()
result = cursor.fetchone()
# result=cursor.fetchone()
print(result)#打印应该是第2条
cursor.scroll(-2,mode='relative') #调整指针,相对当前位置向上移动2位 (第一个参数正数相对当前位置向下移动数值对应指针)
result = cursor.fetchone()
print(result)#调整指针 打印的位置
conn.commit()# 提交,不然无法保存新建或者修改的数据
cursor.close()
conn.close()
# {'sid': 2, 'sname': '陈涛', 'class_id': 1, 'gender': '男'}
# {'sid': 1, 'sname': '刘浩', 'class_id': 1, 'gender': '男'}

相对绝对位置移动mode='absolute'

import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='mysql123',database="day17",charset="utf8")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 受影响的行数
v = cursor.execute('select * from student')
result = cursor.fetchone()
result = cursor.fetchone()
result=cursor.fetchone()
print(result)#打印应该是第三条
cursor.scroll(3,mode='absolute')#调整指针,相对绝对位置移动3位
result = cursor.fetchone()
print(result)
conn.commit()# 提交,不然无法保存新建或者修改的数据
cursor.close()
conn.close()
{'sid': 3, 'class_id': 2, 'sname': '吴一飞', 'gender': ''}
{'sid': 4, 'class_id': 2, 'sname': '姜浩', 'gender': ''}

添加数据库时获取到添加数据的自增id

lastrowid获取添加数据时的自增id
使用方式:
  游标变量.lastrowid
注意:如果是添加的多条数据,获取到的自增id是最后一条的自增id

import pymysql

# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor()

cursor.execute('insert into class(caption) values(%s)',['新班级'])
conn.commit()
new_class_id = cursor.lastrowid # 获取新增数据自增ID

cursor.execute('insert into student(sname,gender,class_id) values(%s,%s,%s)',['李杰','',new_class_id])
conn.commit()

cursor.close()
conn.close()

 

转载于:https://www.cnblogs.com/zjltt/p/7154117.html


http://www.niftyadmin.cn/n/3745536.html

相关文章

小程序循环出来的数据最后一行不要border

.opterList:last-child {border-bottom: none; }在命名后面加last-child; 然后设置border-botton为none 完结撒花!

kubernetes 1.8 安装脚本之ETCD

本次使用环境為:CentOs 7.3Etcd v3.2.9IP组件192.168.2.11etcd1192.168.2.12etcd1192.168.2.13etcd1192.168.2.1宿主机每个虚拟机已经提前安装好了etcd脚步在宿主机上运行,宿主机需要无密ssh各服务器。宿主机需要安装cfsslkubernetes 1.8 安装脚本一共有…

小程序点击复制按钮,复制单号

wxml&#xff1a; <view class"fromItem"><view class"fromLable">退货单号</view><view class"fromValues">{{orderDetail.returnNo}}<view class"copy" bindtap"copyText" data-key"{{o…

钉钉开发系列(二)结构封装

钉钉的每个API接口返回的数据都包含有ErrCode和ErrMsg&#xff0c;由此我们想到可以使用基类来定义&#xff0c;之后的其他数据以继承的方式来达成。所以我们定义一个结果基类。 namespace DDSDK {public class ResultPackage{/// <summary>/// 错误码/// </summary&g…

MFC 带Ribbonbar的窗口 实现全屏和取消全屏

void CMainFrame::FullScreen(){ m_wndRibbonBar.ShowWindow(SW_HIDE);//隐藏工具栏 m_wndStatusBar.ShowWindow(SW_HIDE);//隐藏状态栏 m_menuMainWnd GetMenu(); //隐藏菜单栏 SetMenu(NULL); // 保存以前的位置信息 …

小程序制作二维码和条形码

canvas里的内容就是绘制的二维码 <view style"margin-left:130rpx"><canvas canvas-id"qrcode" style"width:402rpx !important;height:404rpx !important" /></view><view style"margin-top:110rpx;margin-left:77r…

Mac 升级 PHP 7

mac 自带 php, 这个地球人都知道 在新系统中,/usr/bin 成为了系统保护目录&#xff0c;所以我们以前使用的替换 系统 php 的方法行不通了 既然行不通&#xff0c;那就升升级&#xff0c;就用它自带的 php 咯 curl -s http://php-osx.liip.ch/install.sh | bash -s 7.0vi ~/.bas…

小程序循环出来的数据,使用它

设置data-subitem&#xff08;也可以自定义&#xff09; <text class"appoinEwm" bindtap"goTo" data-subitem"{{item}}">预约二维码</text>goTo(options){console.log(e,options)let subitem options.currentTarget.dataset.subit…