当前位置: 首页 > article >正文

Python中通过Pymysql连接MySQL

Python中通过Pymysql连接MySQL

环境

环境:python+mysql

安装pymysql

点击电脑开始菜单—》运行,弹出以下窗口
在这里插入图片描述
或着按快捷键win+r,弹出同样的窗口
输入 cmd,确认。弹出命令提示符窗口

在这里插入图片描述
在窗口中输入

pip install pymysql

在这里插入图片描述
出现以下界面表示成功安装
在这里插入图片描述
连接mysql

import pymysql
conn = pymysql.connect(host = 'localhost', user = 'root', passwd = '密码文本') #链接mysql,地址host:本机;用户名user:root,密码passwd:abc123 
cursor = conn.cursor() 
sql=”create table db1”
cursor.execute(sql)  #新建数据库db1
cursor.execute('use db1') #执行sql语句。使用数据库db1

#或者在connect函数中指定使用的数据库
conn = pymysql.connect(host = 'localhost', user = 'root', passwd = '密码文本', db='db1') 

#操作语句...

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

新建数据库

Sql=”create table db1”
Cursor.execute(sql)
sl='use db1'
cursor.execute(sl) #使用新建的数据库

建表

sql="create table student(id int Unsigned Primary Key Auto_Increment,name varchar(20),yuwen int)"
cursor.execute(sql)

插入数据

cursor.execute('use db1') 
cursor.execute("Insert Into student Values(Null, '小明', 86))
cursor.connection.commit()#加入,否则插入不成功 

为了安全,推荐使用占位符

sql = "insert into student Values(Null,%s,%s)" 
values = ('王芳', 92) 
cursor.execute(sql,values) 
cursor.connection.commit()#加入,否则插入不成功

查询

sl="select * from student" 
n=cursor.execute(sl) #n是得到记录条数 ,如果没有匹配的结果时,n=0

result = cursor.fetchall() #用cursor.fetchall()获取所有结果。如果匹配的结果为0,返回()
ans1 = result[0]
ans2 = result[1]

或则用cursor.fetchone(),获取一个记录,如果有多条记录,运行一次读取一个结果。

ans1 = cursor.fetchone()
ans2 = cursor.fetchone()

带筛选的查询

sl="select * from student where yuwen>%s" 
values=(90,)
n=cursor.execute(sl,values) #n是得到记录条数 
bb=cursor.fetchone() #获取一条记录,如有多条记录,运行一次读取一个记录

模糊查询

转移转义符

转义符说明
%0或多个字符
_单个字符
sl="select * from student where name like %s" 
values=('%小%',)
n=cursor.execute(sl,values)#包含有abc的字符 
bb=cursor.fetchone()

‘%abc%’ 包含有abc的字符
‘%abc’ 以abc结尾的字符
‘abc%’ 以abc开头的字符


http://www.kler.cn/a/551453.html

相关文章:

  • SoftwareCluster中如何配置VendorSignature
  • 机器学习_14 随机森林知识点总结
  • flink反压详解
  • Android 10.0 移除wifi功能及相关菜单
  • Android中kotlin的Map简单使用方法
  • 【现代深度学习技术】深度学习计算 | GPU
  • STM32 ADC介绍(硬件原理篇)
  • Linux的SSH无法连接(shell request failed on channel 0)
  • Dockerfile 详解:构建自定义镜像
  • AUTO TECH China 2025 广州国际汽车技术展览会:引领汽车科技新潮流
  • 日常问题-pnpm install执行没有node_modules生成
  • OpenHarmony 系统性能优化——默认关闭全局动画
  • DeepSeek教unity------Dotween
  • 网络安全学习笔记之Internet基本知识
  • 开发一个交易所需要哪些技术
  • 算法-栈括号匹配
  • Go语言的游戏开发
  • 视点坐标及鼠标交点坐标的信息显示(七)
  • HBuilderX中uni-app打开页面时,如何用URL传递参数,Query参数传递
  • docker拉取失败received unexpected Http status:500 Internal Server Error