Python-pymysql操作MySQL数据库
一、安装pymysql
py -m pip install pymysql;
二、pymysql数据库操作
1.简单示例
#coding=utf-8
import pymysql
## 打开数据库连接
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "test",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
print(cursor)
print(type(cursor))
2.创建数据库
#coding=utf-8
import pymysql
try:
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234"
)
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS grdb DEFAULT CHARSET utf8 COLLATE utf8_general_ci;")
cur.close()
conn.close()
print("创建数据库pythonDB成功! ")
except pymysql.Error as e:
print("Mysql Error %d: %s" %(e.args[0],e.args[1]))
#COLLATE utf8_general_ci:大小写不敏感
3.创建表
#coding=utf-8
import pymysql
try:
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234") conn.select_db('grdb') ## 选择pythonDB数据库
cur = conn.cursor() ## 获取游标
## 如果所建表已存在,删除重建
cur.execute("drop table if exists User;")
## 执行建表sql语句
cur.execute('''CREATE TABLE User (id int(11) DEFAULT NULL,name varchar(255) DEFAULT NULL,password varchar(255) DEFAULT NULL,birthday date DEFAULT NULL)ENGINE=innodb DEFAULT CHARSET=utf8;''')
cur.close()
conn.close()
print(u"创建数据表成功")
except pymysql.Error as e:
print("Mysql Error %d: %s" %(e.args[0],e.args[1]))
4.插入表数据
#coding=utf-8
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "grdb",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
## 方式一:直接执行insert语句,插入一条数据
insert = cursor.execute("insert into user values(1,'Tom','123','1990-01-01')")
print(u"添加语句受影响的行数:",insert)
## 方式二:通过格式字符串传入值,此方式可以防止SQL注入
sql = "insert into user values(%s,%s,%s,%s)"
insert = cursor.execute(sql,(3,'lucy','efg','1993-02-01'))
print(u"添加语句受影响的行数:",insert)
## 关闭游标
cursor.close()
## 提交事务
conn.commit()
## 关闭数据库连接
conn.close()
print(u"sql语句执行成功!")
5.查询表数据语句
(1)逐条获取fetchone()
#coding=utf-8
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "grdb",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
cursor.execute("select * from user")
while 1:
res = cursor.fetchone()
if res is None:
## 表示已经取完结果集
break
print(res)
## 将读取到的时间格式化
print(res[-1].strftime("%Y-%m-%d"))
## 关闭游标
cursor.close()
## 提交事务
conn.commit()
## 关闭数据库连接
conn.close()
print("sql语句执行成功!")
#cursor.fetchone 一条一条获取数据,每条数据是元组
(2)获取n条数据fetchmany(n)
#coding=utf-8
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "grdb",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
cursor.execute("select * from user")
## 获取游标处两条数据
resTuple = cursor.fetchmany(2)
print("结果集类型:",type(resTuple))
for i in resTuple:
print(i)
## 关闭游标
cursor.close()
## 提交事务
conn.commit()
## 关闭数据库连接
conn.close()
print("sql语句执行成功!")
#cursor.fetchmany 获取前两行数据,每条数据是元组
(3)获取所有数据fetchall()
#coding=utf-8
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "grdb",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
cursor.execute("select * from user")
## 获取所有的数据
resTuple = cursor.fetchall()
print("结果集类型:",type(resTuple))
for i in resTuple:
print(i)
## 关闭游标
cursor.close()
## 提交事务
conn.commit()
## 关闭数据库连接
conn.close()
print("sql语句执行成功!")
#cursor.fetchall 获取数据,每条数据是元组
6.更新数据
#coding=utf-8
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "grdb",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
## 查询一条数据
query = cursor.execute("select * from user")
print("表中所有数据:")
for i in cursor.fetchall():
print(i)
## 批量更新数据
cursor.executemany("update user set password = %s where name=%s",[('tomx2x', 'tom'), ('amy2x', 'amy')])
## 查看更新后的结果
query = cursor.execute("select * from user")
print("表中所有数据:")
for i in cursor.fetchall():
print(i)
## 关闭游标
cursor.close()
## 提交事务
conn.commit()
## 关闭数据库连接
conn.close()
print("sql语句执行成功!")
7.删除数据
#coding=utf-8
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "lgb",
passwd = "Lgb@1234",
db = "grdb",
charset = "utf8")
## 使用cursor()方法获取数据库的操作游标
cursor = conn.cursor()
cursor.execute("select * from user")
print("表中所有数据:")
for i in cursor.fetchall():
print(i)
## 删除数据
delete = cursor.execute("delete from user where name='tom'")
print("删除语句影响的行数:",delete)
print("删除一条数据后,表中数据:")
cursor.execute("select * from user")
for i in cursor.fetchall():
print(i) ## 关闭游标
cursor.close()
## 提交事务
conn.commit()
## 关闭数据库连接
conn.close()
print("sql语句执行成功!")
Python-pymysql操作MySQL数据库的更多相关文章
- python 之操作mysql 数据库实例
对于python操作mysql 数据库,具体的步骤应为: 1. 连接上mysql host 端口号 数据库 账号 密码2. 建立游标3. 执行sql(注意,如果是update,insert,delet ...
- python使用pymysql操作mysql数据库
1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...
- flask + pymysql操作Mysql数据库
安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...
- Python之 操作 MySQL 数据库
什么是MySQLdb? MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的. 安装 Pytho ...
- python+pymysql访问mysql数据库
今天跟大家分享两种场景的python连接MySQL方法: 场景一:连接远程MySQL 首先,安装pymysql:在命令行执行pip install pymysql指令. 然后,导入pymysql: i ...
- 【20】python之操作MySQL数据库
一.连接库安装 Python2.x:MySQLdb Python3.x :pymysql 二.接口信息 #创建数据库连接 pymysql.Connect()参数说明 host(str): MySQL服 ...
- 用pymysql操作MySQL数据库
工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...
- python实现操作mysql数据库
实现代码如下: #mysql数据库的查询等 import pymysql from xctest_tools.xc_ReadFile.get_ReadTxt import * class mysql: ...
- python 3.6 +pyMysql 操作mysql数据库
版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...
- python pymysql 连接 mysql数据库进行操作
1.数据库的连接操作 import pymysql conn = pymysql.connect(host=', db='oldboydb') # host表示ip地址,user表示用户名,passw ...
随机推荐
- Kafka 社区KIP-405中文译文(分层存储)
原文链接:https://cwiki.apache.org/confluence/display/KAFKA/KIP-405%3A+Kafka+Tiered+Storage 译者:Kafka KIP- ...
- 2023全国大学生电子设计竞赛H题全解 [原创www.cnblogs.com/helesheng]
2023年又是全国大学生电子设计竞赛年,一如既往的指导学生死磕H题.8月2日看到公布的赛题,我自己还沾沾自喜,觉得今年学生用嵌入式系统和数字信号处理知识就可以完成这题,赛前都辅导过,应该成绩不差.哪想 ...
- vim处理冲突文件
一.文件冲突前: 二.文件冲突后(默认为): 此时编辑文档,将before改为after但是异常退出了,此时编辑文档提示冲突: 回车进入展示编辑前的文档: ll-a可查看到隐藏文件的信息: 三.文件冲 ...
- TOEFL | Reading · 题型总结
目录 直接引用 - 直译题(不要读文章) 直接引用 - why 题(需要细读题干) 直接引用 - 其他(需要细读题干) 理解题(出现最多,需要细读题干) 转义题(不要读题干) 添加句子题(不要读题干) ...
- The container name "/nacos" is already in use by container
转载请注明出处: 服务器上使用docker 安装启动 nacos 的时候,报 The container name "/nacos" is already in use by co ...
- spring cloud 通过feign请求设置请求头
本文为博主原创,转载请注明出处: spring cloud 服务组件之间通过feign 的方式请求,会携带很少的基础类型的消息头参数,比如Content-Type等,但不会携带自定义或指定的请求头参数 ...
- 文件传输中的MD5校验技术
1. 文件的MD5校验简介 文件的MD5校验是一种常用的文件完整性验证方法.MD5(Message Digest Algorithm 5)是一种广泛应用的哈希算法,它能够将任意长度的数据转换为固定长度 ...
- 在TypeScript项目中搭配Axios封装后端接口调用
前言 本来是想发 next.js 开发笔记的,结果发现里面涉及了太多东西,还是拆分出来发吧~ 本文记录一下在 TypeScript 项目里封装 axios 的过程,之前在开发 StarBlog-Adm ...
- [转帖]Run Grafana behind a reverse proxy
On this page Introduction Configure NGINX Configure HAProxy Configure IIS Configure Traefik Summary ...
- [转帖]Region Merge Config
TiKV replicates a segment of data in Regions via the Raft state machine. As data writes increase, a ...