Python3使用PyMySQL操作数据库
1. 安装PyMySQL
pip install PyMySQL
2. 创建表
在某个数据库内,使用以下指令建表
CREATE TABLE `users`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8 COLLATE=utf8_bin
3. 使用PyMySQL执行增删改查
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019-1-7 15:43
# @Author : Z.C.Wang
# @Email : iwangzhengchao@gmail.com
# @File : PyConnectionMySQL.py
# @Software: PyCharm Community Edition
"""
Description :
pymysql.Connect()参数说明
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
passwd(str): 密码
db(str): 数据库名称
charset(str): 连接编码 connection对象支持的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接 cursor对象支持的方法
execute(sql, args) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchall() 获取结果集中的所有行
close() 关闭游标对象
"""
import pymysql # 连接数据库
connection = pymysql.connect(host='localhost', user='root', password='root',
db='test', charset='utf8') if connection.open:
print('the connection is open...') # 清空users表
cursor = connection.cursor()
cursor.execute("truncate table users")
connection.commit() # (1)批量插入
record = []
for i in range(10):
email = "mail_" + str(i) + "@qq.com"
password = "xxx_" + str(i)
record.append((email, password)) try:
sql = "insert into users (email, password) values (%s, %s)"
rows = cursor.executemany(sql, record)
connection.commit()
print("insert success. affected rows : %d" % rows)
except:
print("insert ERROR.")
connection.rollback() # (2)删除记录
try:
sql = "delete from users where id=1"
rows = cursor.execute(sql)
connection.commit()
print("delete success. affected rows : %d" % rows)
except:
print("delete ERROR.")
connection.rollback() # (3)修改记录
try:
sql = "update users set password='yyy' where id=5"
rows = cursor.execute(sql)
connection.commit()
print("update success. affected rows : %d" % rows)
except:
print("update ERROR.")
connection.rollback() # (4)查询记录
try:
sql = 'select * from users'
count = cursor.execute(sql)
print("number of record in users: %d" % count)
result = cursor.fetchall()
for row in result:
print(row)
connection.commit()
except:
print("query ERROR.")
connection.rollback() # 关闭连接
cursor.close()
connection.close()
print("connection close.")
运行结果:
D:\Python3.6_2\python.exe E:/PycharmProjects/PyConnectionMySQL/PyConnectionMySQL.py
the connection is open...
insert success. affected rows : 10
delete success. affected rows : 1
update success. affected rows : 1
number of record in users: 9
(2, 'mail_1@qq.com', 'xxx_1')
(3, 'mail_2@qq.com', 'xxx_2')
(4, 'mail_3@qq.com', 'xxx_3')
(5, 'mail_4@qq.com', 'yyy')
(6, 'mail_5@qq.com', 'xxx_5')
(7, 'mail_6@qq.com', 'xxx_6')
(8, 'mail_7@qq.com', 'xxx_7')
(9, 'mail_8@qq.com', 'xxx_8')
(10, 'mail_9@qq.com', 'xxx_9')
connection close. Process finished with exit code 0
Python3使用PyMySQL操作数据库的更多相关文章
- Python学习(二十九)—— pymysql操作数据库优化
转载自:http://www.cnblogs.com/liwenzhou/articles/8283687.html 我们之前使用pymysql操作数据库的操作都是写死在视图函数中的,并且很多都是重复 ...
- pymysql操作数据库、索引、慢日志管理
目录 pymysql操作数据库 简单操作 sql的注入问题 sql注入问题解决办法 sql注入问题模板总结 利用pymysql操作数据库 (增删改),conn.commit() 索引 1.为何要有索引 ...
- pymysql 操作数据库
一.简介 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,但目前pymysql支持python3.x而后者不支持3.x版本 其执行语句与sql源码相似 二.使用 ...
- Python使用PyMysql操作数据库
安装 pip install -U pymysql 连接数据库 连接数据库有两种不同的格式 直接使用参数 代码如下 import pymysql.cursors connection = pymysq ...
- 使用pymysql操作数据库
学习如何使用python的pymysql模块来操作mysql数据库 这里的基本用法主要借鉴了该篇博客:https://www.cnblogs.com/woider/p/5926744.html 因为这 ...
- 用pymysql操作数据库
import pymysql # 打开数据库连接 connection = pymysql.connect(host='127.0.0.1', user='root', passwd=', db='s ...
- MySQL-注释-Navicat基本使用-复杂查询练习题-解题思路-pymysql操作数据库-SQL注入-05
目录 mysql语句注释 navicat 的基本使用 特色(个人总结) 与数据服务器建立连接 创建&打开数据库.表 创建 打开 修改操作表结构 修改表结构 查询修改操作表数据 基本语句对应的操 ...
- pymysql操作数据库
pymysql.connect()参数说明:(连接数据库时需要添加的参数)host(str): MySQL服务器地址port(int): MySQL服务器端口号user(str): 用户名passwd ...
- python(pymysql操作数据库)
第一种方式 import pymysql # 打开数据库连接 db = pymysql.connect(host="192.168.88.11", user="root& ...
随机推荐
- bzoj 4530: [Bjoi2014]大融合【LCT】
新姿势,一般来讲LCT只能维护splay重边里的数据,而这里要求维护整颗子树的size 多维护一个sq表示当前点轻儿子的size和,si表示包括轻重边的整颗子树的大小 然后需要改sq的地方是link和 ...
- mycat启动报错UnknownHostException(Temporary failure in name resolution)解决方法
重启命令 ./mycat restart 查看日志 cd logs tail -f wrapper.log 报错信息 INFO | jvm 2 | 2018/05/09 11:28:28 | Erro ...
- 字符串处理 Codeforces Round #305 (Div. 2) A. Mike and Fax
题目传送门 /* 字符串处理:回文串是串联的,一个一个判断 */ #include <cstdio> #include <cstring> #include <iostr ...
- ACM_扫雷(dfs)
扫雷 Time Limit: 2000/1000ms (Java/Others) Problem Description: 扫雷这个游戏想必各位都是会玩的吧.简单说一下规则,n行m列的格子地图上有分布 ...
- 关于BMP
关于BMP位图的资料网上有很多,内容也比较基础.本文实现BMP位图的读取.显示.保存,并对一些重要的问题进行说明(包括字节对齐.内存中的存储顺序.调色板). BMP文件共包括文件头.信息头.调色板(位 ...
- Eclipse显示空白符,及使用google代码格式化
启动Eclipse,打开Preferences对话框.菜单“window”-“Preferences”. 找到Text Editors,勾选show whitespace characters,如图: ...
- 取URL中各个参数的值
取参数值的方法有很多,个人记录一个方便好用的 //查询参数(参数名)function GetQueryString(name) { var reg = new RegExp("(^|& ...
- synchronize早已经没那么笨重
我发现一些同学在网络上有看不少synchronize的文章,可能有些同学没深入了解,只看了部分内容,就急急忙忙认为不能使用它,很笨重,因为是采用操作系统同步互斥信号量来实现的.关于这类的对于synch ...
- ios app跳转拨打电话界面,调用拨打电话功能
DNLogFUNC //两种方法都可以用 //这种据说是可以上appstore NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithF ...
- iOS开发之cell位置contentOffset的用法
@property(nonatomic) CGPoint contentOffset; // default ...