python的pymysql使用方法【轉】

前言html

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

本文測試python版本:2.6.6。mysql版本:5.7.17mysql

1、安裝sql

pip install pymysql

2、使用操做數據庫

建立測試環境python3.x

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判斷spa

#!/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() #關閉鏈接

執行.net

 

 

 二、獲取新建立數據自增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()

 

 

轉自

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

相關文章
相關標籤/搜索