python的pymysql使用方法【转】

前言python

pymsql是Python中操做MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x然后者不支持3.x版本。mysql

本文测试python版本:2.6.6。mysql版本:5.7.17sql

1、安装数据库

pip install pymysql

2、使用操做python3.x

建立测试环境ide

mysql> create database zst;
Query OK, 1 row affected (0.03 sec)

mysql> use zst
Database changed

mysql> create table tb(id int not null auto_increment, user varchar(64),pass varchar(64),licnese varchar(64),primary key(id));
Query OK, 0 rows affected (0.08 sec)

mysql> insert into tb(user,pass,licnese)values("u1","u1pass","11113");
Query OK, 1 row affected (0.11 sec)

mysql> insert into tb(user,pass,licnese)values("u2","u2pass","11113");
Query OK, 1 row affected (0.05 sec)

mysql> insert into tb(user,pass,licnese)values("u3","u3pass","11113");
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb(user,pass,licnese)values("u5","u5pass","11113");
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb(user,pass,licnese)values("u6","u6pass","11113");
Query OK, 1 row affected (0.01 sec)

mysql> select * from tb;
+----+------+--------+---------+
| id | user | pass | licnese |
+----+------+--------+---------+
| 1 | u1 | u1pass | 11113 |
| 2 | u2 | u2pass | 11113 |
| 3 | u3 | u3pass | 11113 |
| 4 | u4 | u4pass | 11113 |
| 5 | u5 | u5pass | 11113 |
| 6 | u6 | u6pass | 11113 |
+----+------+--------+---------+
6 rows in set (0.00 sec)

 

一、查询测试

#!/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()

执行fetch

 

加入try判断blog

#!/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() #关闭链接

执行ip

 

 

 二、获取新建立数据自增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","11113"),("u4","u4pass","22224")])
conn.commit()
cursor.close()
conn.close()
#获取自增id
new_id = cursor.lastrowid      
print new_id

查询结果

mysql> select * from tb;

+----+------+--------+---------+ | id | user | pass | licnese | +----+------+--------+---------+ | 1 | u1 | u1pass | 11113 | | 2 | u2 | u2pass | 11113 | | 3 | u3 | u3pass | 11113 | | 4 | u4 | u4pass | 11113 | | 5 | u5 | u5pass | 11113 | | 6 | u6 | u6pass | 11113 | | 7 | u3 | u3pass | 11113 | | 8 | u4 | u4pass | 22224 | +----+------+--------+---------+ 8 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)

 

三、更新操做

#!/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)

 

四、删除操做

#!/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 |
+----+----------+----------+
|  1 | hch      | 11113    |
|  2 | hch1     | 11114    |
|  4 | liu      | 1234     |
|  5 | liu      | 1234     |
+----+----------+----------+
4 rows in set (0.00 sec)

 

 

五、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()