python的pymysql使用方法【转】

时间:2023-03-09 01:31:21
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()

执行

python的pymysql使用方法【转】

加入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() #关闭连接

执行

python的pymysql使用方法【转】

 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)

python的pymysql使用方法【转】

 加入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 数据库及 简单的增删改查操作 - ****博客
https://blog.****.net/qq_37176126/article/details/72824106

Python中操作mysql的pymysql模块详解 - 明天OoO你好 - 博客园
http://www.cnblogs.com/wt11/p/6141225.html