python的pymysql使用方法【转】
前言
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
本文测试python版本:2.6.6。mysql版本:5.7.17
一、安装
pip install pymysql
二、使用操作
创建测试环境
mysql> create database zst;
Query OK, row affected (0.03 sec) mysql> use zst
Database changed mysql> create table tb(id int not null auto_increment, user varchar(),pass varchar(),licnese varchar(),primary key(id));
Query OK, rows affected (0.08 sec) mysql> insert into tb(user,pass,licnese)values("u1","u1pass","");
Query OK, row affected (0.11 sec) mysql> insert into tb(user,pass,licnese)values("u2","u2pass","");
Query OK, row affected (0.05 sec) mysql> insert into tb(user,pass,licnese)values("u3","u3pass","");
Query OK, row affected (0.00 sec) mysql> insert into tb(user,pass,licnese)values("u5","u5pass","");
Query OK, row affected (0.00 sec) mysql> insert into tb(user,pass,licnese)values("u6","u6pass","");
Query OK, row affected (0.01 sec) mysql> select * from tb;
+----+------+--------+---------+
| id | user | pass | licnese |
+----+------+--------+---------+
| | u1 | u1pass | |
| | u2 | u2pass | |
| | u3 | u3pass | |
| | u4 | u4pass | |
| | u5 | u5pass | |
| | u6 | u6pass | |
+----+------+--------+---------+
rows in set (0.00 sec)
1、查询
#!/usr/bin/python
#coding: utf-8
import sys
import os
import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3307, user='root', passwd='hch123', db='zst', charset='utf8') # 创建游标
cursor = conn.cursor() # 执行SQL
cursor.execute("select * from tb") # 获取剩余结果的第一行数据
row_1 = cursor.fetchone()
print row_1 # 获取剩余结果前n行数据
row_2 = cursor.fetchmany(3)
print row_2 # 获取剩余结果所有数据
row_3 = cursor.fetchall()
print row_3 conn.commit()
cursor.close()
conn.close()
执行

加入try判断
#!/usr/bin/python
#coding: utf-8
import pymysql #导入 pymysql #打开数据库连接
db= pymysql.connect(host="localhost",user="root",
password="hch123",db="zst",port=3307) # 使用cursor()方法获取操作游标
cur = db.cursor() #1.查询操作
# 编写sql 查询语句 user 对应我的表名
sql = "select * from user"
try:
cur.execute(sql) #执行sql语句 results = cur.fetchall() #获取查询的所有记录
print("id","name","password")
#遍历结果
for row in results :
id = row[0]
name = row[1]
password = row[2]
print(id,name,password)
except Exception as e:
raise e
finally:
db.close() #关闭连接
执行

2、获取新创建数据自增ID
可以获取到最新自增的ID,也就是最后插入的一条数据ID
#!/usr/bin/python
#coding: utf-8 import sys
import os
import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3307, user='root', passwd='hch123', db='zst') # 创建游标
cursor = conn.cursor() # 执行SQL
effect_row = cursor.executemany("insert into tb(user,pass,licnese)values(%s,%s,%s)", [("u3","u3pass",""),("u4","u4pass","")])
conn.commit()
cursor.close()
conn.close()
#获取自增id
new_id = cursor.lastrowid
print new_id
查询结果
mysql> select * from tb; +----+------+--------+---------+
| id | user | pass | licnese |
+----+------+--------+---------+
| | u1 | u1pass | |
| | u2 | u2pass | |
| | u3 | u3pass | |
| | u4 | u4pass | |
| | u5 | u5pass | |
| | u6 | u6pass | |
| | u3 | u3pass | |
| | u4 | u4pass | |
+----+------+--------+---------+
rows in set (0.00 sec)

加入try判断的python脚本
#!/usr/bin/python
#coding: utf-8 import pymysql #导入 pymysql #打开数据库连接
db= pymysql.connect(host="localhost",user="root",
password="hch123",db="zst",port=3307) # 使用cursor()方法获取操作游标
cur = db.cursor() sql_insert ="""insert into user(id,username,password) values(5,'liu','1234')""" try:
cur.execute(sql_insert)
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
执行
[root@hchtest3 ~]# python insert_try.py mysql> select * from zst.user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | hch | 11113 |
| 2 | hch1 | 11114 |
| 3 | hch2 | 11115 |
| 4 | liu | 1234 |
| 5 | liu | 1234 |
+----+----------+----------+
5 rows in set (0.00 sec)
3、更新操作
#!/usr/bin/python
#coding: utf-8 import pymysql #导入 pymysql #打开数据库连接
db= pymysql.connect(host="localhost",user="root",
password="hch123",db="zst",port=3307) # 使用cursor()方法获取操作游标
cur = db.cursor() sql_update ="update user set username = '%s' where id = %d" try:
cur.execute(sql_update % ("xiongda",3)) #像sql语句传递参数
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
执行
mysql> select * from zst.user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | hch | 11113 |
| 2 | hch1 | 11114 |
| 3 | xiongda | 11115 |
| 4 | liu | 1234 |
| 5 | liu | 1234 |
+----+----------+----------+
5 rows in set (0.00 sec)
4、删除操作
#!/usr/bin/python
#coding: utf-8 import pymysql #导入 pymysql #打开数据库连接
db= pymysql.connect(host="localhost",user="root",
password="hch123",db="zst",port=3307) # 使用cursor()方法获取操作游标
cur = db.cursor() sql_delete ="delete from user where id = %d" try:
cur.execute(sql_delete % (3)) #像sql语句传递参数
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
执行
mysql> select * from zst.user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| | hch | |
| | hch1 | |
| | liu | |
| | liu | |
+----+----------+----------+
rows in set (0.00 sec)
5、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')
#游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select * from tb7") row_1 = cursor.fetchone()
print row_1 #{u'licnese': 213, u'user': '123', u'nid': 10, u'pass': '213'} conn.commit()
cursor.close()
conn.close()
转自
python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作 - CSDN博客
https://blog.csdn.net/qq_37176126/article/details/72824106
Python中操作mysql的pymysql模块详解 - 明天OoO你好 - 博客园
http://www.cnblogs.com/wt11/p/6141225.html
python的pymysql使用方法【转】的更多相关文章
- python之pymysql模块学习(待完善...)
pymysql介绍 pymysql是在python3.x版本中用于连接mysql服务器的一个库.python2中则使用mysqldb. 安装方法: pip install pymysql 使用实例: ...
- python 调用pymysql模块遇到\转义问题解决办法
1.问题情况 本来存入mysql的是字典,有汉字,由于python版本是2.7,所以在json的时候把我的值变成了unicode,那么在调用pymysql的时候,mysql给我转义取消了. 存之前: ...
- python的pymysql模块简介
一.介绍 在python中用pymysql模块来对mysql进行操作,该模块本质就是一个套接字客户端软件,使用前需要事先安装 pip3 install pymysql 二.操作简介 import py ...
- Python进阶----pymysql的安装与使用,mysql数据库的备份和恢复,mysql的事务和锁
Python进阶----pymysql的安装与使用,mysql数据库的备份和恢复,mysql的事务和锁 一丶安装 pip install PyMySQL 二丶pymysql连接数据库 ### 语法: ...
- Python进阶----pymysql模块的使用,单表查询
Python进阶----pymysql模块的使用,单表查询 一丶使用pymysql 1.下载pymysql包: pip3 install pymysql 2.编写代码 ...
- Python 之 PyMySQL 安装和使用
Python具有内置的SQLite支持. 在本节中,我们将学习使用MySQL的相关概念和知识. 在早期Python版本一般都使用MySQLdb模块,但这个MySQL的流行接口与Python 3不兼容. ...
- python 类属性与方法
Python 类属性与方法 标签(空格分隔): Python Python的访问限制 Python支持面向对象,其对属性的权限控制通过属性名来实现,如果一个属性有双下划线开头(__),该属性就无法被外 ...
- Python执行系统命令的方法 os.system(),os.popen(),commands
os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...
- python 调用 shell 命令方法
python调用shell命令方法 1.os.system(cmd) 缺点:不能获取返回值 2.os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等 ...
随机推荐
- perl trick
一.die if以及文件的操作 #!/usr/bin/perl -w use strict; die "USAGE:\n\tperl $0 <><><>\ ...
- NGINX X-Forwarded-For / XFF / xforword
s https://en.wikipedia.org/wiki/X-Forwarded-For http://www.cnblogs.com/yihang/archive/2010/12/19/191 ...
- Windows2012 要远程登录,你需要具有通过远程桌面服务进行登录的权限.
直接说正题... 提示如下: 解决办法: gpedit进入策略组:计算机配置->Windows设置->安全设置->本地策略->用户权限分配,找到拒绝通过远程桌面服务登录,把里面 ...
- 在js或jquery中动态添加js脚本【转】
起因: 我们在用js动态写入script时,会导致</script>后面的所有语句都变为普通文本,导致html展示无效, 所以我们需要规避</script>问题. 解决方案一( ...
- js取指定范围随机值【原】
js取指定范围随机值 <HTML> <HEAD> <meta http-equiv="content-Type"content="text/ ...
- 【1】【leetcode-76】 最小覆盖子串
最小覆盖子串(hard) (不会) 给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串. 示例: 输入: S = "ADOBECODEBANC", ...
- css的几个小技巧
本文收录css设置样式的一些小技巧 1. 设置文字在块级标签居中(包括水平居中和垂直居中) 水平居中 方法一:使用text-align text-align:center 方法二:目标标签的父级标签设 ...
- tomcat源码研究之源码导入eclipse
版本:8.5.x官网:https://tomcat.apache.org/svn.html1. 下载源码,git镜像:https://github.com/apache/tomcat85 .2. 导入 ...
- IIS7.5配置过程
1.Windows功能,注意选择应用程序开发功能,否则不能使用经典模式. 2.Cmd运行(使用.netframework4.0)C:\Windows\Microsoft.NET\Framework\V ...
- C# 常用的工具方法
1.DateTime 转为Unix的long的时间戳 long orderTime = order.AddTime.ToUnixTimeStamp("Milliseconds"); ...