python中pymysql模塊操做與使用


pymysql模塊使用————(實操)


該軟件包包含一個純Python MySQL客戶端庫。PyMySQL的目標是成爲MySQLdb的替代品,並在CPython,PyPy和IronPython上工做。python

注:PyMySQL不支持低級別的API _mysql提供了像data_seek, store_resultuse_result。您應該使用PEP 249中定義的高級API 。可是支持一些API,如自動提交ping,由於PEP 249不包含他們的用例。mysql

要求

  • Python - 如下之一:web

    • CPython:2.7和> = 3.4sql

    • PyPy:最新版本數據庫

  • MySQL服務器 - 如下之一:服務器

安裝

Package上傳到PyPIfetch

你也能夠用pip安裝它:spa

pip3 install pymysql

安裝完成以後便可使用了。咱們先看看官方的示例:

一.建立一個SQL表

  1. CREATE TABLE `users` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `email` varchar(255) COLLATE utf8_bin NOT NULL,
        `password` varchar(255) COLLATE utf8_bin NOT NULL,
        PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_binAUTO_INCREMENT=1 ;

二.python使用實例:

import pymysql.cursors

# 鏈接到數據庫
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='123',
                             db='books',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # 插入新的數據
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # 默認狀況下,鏈接不是自動提交。因此你必須自行保存好
    connection.commit()

    with connection.cursor() as cursor:
        # 讀取單個記錄
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

執行後的結果:

blob.png

說明:這裏是以字典爲返回結果


1、學習實例操做

實例一:實現:使用Python實現用戶登陸,若是用戶存在則登陸成功(假設該用戶已在數據庫中)

import pymysql

user = input('請輸入用戶名:')
pwd = input('請輸入密碼:')

#1.鏈接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db = 'dbtest',
    charset='utf8'
)
#2.建立遊標
cursor = conn.cursor()
###注意%s須要加引號
sql = "select * from db2 where username = '{}' and password='{}' ".format(user,pwd)
print(sql)

#3.執行sql語句
cursor.execute(sql)
result=cursor.execute(sql) #執行sql語句,返回sql查詢成功的記錄數目
print(result)

#4.關閉鏈接,遊標和鏈接都要關閉
cursor.close()
conn.close()

if result:
    print('登陸成功!')
else:
    print('登陸失敗!')

執行後的結果:

blob.png


2、execute()之sql注入

這裏只截圖演示三種SQL注入示例截圖

1

blob.png

2

blob.png

3

blob.png

解決方法: 

# 原來是咱們對sql進行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(username,pwd)
# print(sql)
# result=cursor.execute(sql)

#改寫爲(execute幫咱們作字符串拼接,咱們無需且必定不能再爲%s加引號了)
sql="select * from userinfo where name=%s and password=%s" #!!!注意%s須要去掉引號,由於pymysql會自動爲咱們加上
result=cursor.execute(sql,[user,pwd]) #pymysql模塊自動幫咱們解決sql注入的問題,只要咱們按照pymysql的規矩來。


3、增、刪、改:conn.commit()

commit()方法:在數據庫裏增,刪,改的時候。必需要進行提交,不然插入的時候數據不生效

import pymysql

username = input('請輸入用戶名:')
pwd = input('請輸入密碼:')

#1.鏈接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db='dbtest',
    charset='utf8'
)

#2.建立遊標
cursor = conn.cursor()

#操做
#增
# sql = "insert into db2(username,password) values (%s,%s)"
#
# effect_row = cursor.execute(sql,(username,pwd))
# #同時插入多條數據
# cursor.executemany(sql,[('lisi','110'),('wangwu','119')])
# print(effect_row)

#改
# sql = "update db2 set username = %s where  id = 2"
# effect_row=cursor.execute(sql,username)
# print(effect_row)

#刪
# sql = "delete from db2 where id =n 2"
# effect_row = cursor.execute(sql,username)
# print(effect_row)


#必定記得commit
conn.commit()

# 4.關閉遊標
cursor.close()


4、查:fetchone、fetchmany、fetchall

fetchone():獲取下一行數據,第一次爲首行;
fetchall():獲取全部行數據源
fetchmany(4):獲取4行數據


使用fetchone()

import pymysql

#1.鏈接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password ='123',
    db='dbtest',
    charset='utf8'
)

#2.建立遊標
cursor = conn.cursor()

sql = 'select * from db2'
cursor.execute(sql)

#3.查詢數據
row = cursor.fetchone()
print(row)

#查詢第二行數據
row = cursor.fetchone()
print(row)

#4.關閉遊標
cursor.close()

#5.關閉鏈接
conn.close()

執行後輸出的結果:

blob.png


使用fetchall()

import pymysql

#1.鏈接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db = 'dbtest',
    charset='utf8'
)

#2.建立遊標
cursor = conn.cursor()

sql = 'select * from db2'
cursor.execute(sql)

#3.獲取全部的數據
rows = cursor.fetchall()
print(rows)

#4.關閉遊標
cursor.close()

#5.關閉鏈接
conn.close()

執行後輸出結果:

blob.png


使用fetchall()

import pymysql

#1.鏈接
conn = pymysql.connect(
    host = 'localhost',
    port=3306,
    user = 'root',
    password = '123',
    db = 'dbtest',
    charset = 'utf8'
)

#2.建立遊標
cursor = conn.cursor()

sql = 'select * from db2'
cursor.execute(sql)

#3.獲取數據
rows = cursor.fetchall()
print(rows)

#4.關閉遊標
cursor.close()

#5.關閉鏈接
conn.close()

執行輸出結果:

blob.png

默認狀況下,咱們獲取到的返回值是元祖,只能看到每行的數據,殊不知道每一列表的是什麼,這個時候可使用如下方式來返回字典,每一行的數據都會生成一個字典:

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  #在實例化的時候,將屬性cursor設置爲pymysql.cursors.DictCursor

在fetchone示例中,在獲取數據的時候,能夠理解開始的時候,有一個行指針指着第一行的上方,獲取一行,它就向下移動一行,因此當行指針到最後一行的時候,就不能在獲取到行的內容,因此咱們可使用以下方法來移動行指針:

cursor.scroll(1,mode='relative')  #相對當前位置移動
cursor.scroll(2,mode='absolute')  #相對絕對位置移動
第一個值爲移動的行動,整數爲向下移動,負數爲向下移動,mode指定了是相對當前位置移動,仍是相對於行首移動

用戶登陸實例二:

import pymysql

#1.鏈接
conn = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    password = '123',
    db = 'dbtest',
    charset = 'utf8'
)

#2.建立遊標
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = 'select * from db2'
cursor.execute(sql)

#3.查詢數據
# 查詢第一行的數據

row = cursor.fetchone()
print(row)

# 查詢第二行數據
row = cursor.fetchone()
print(row)

cursor.scroll(-1,mode='relative') #設置以後,光標相對當前位置往前移動了一行,因此打印的結果爲第二行的數據
row = cursor.fetchone()
print(row)

cursor.scroll(-1,mode='relative') #設置以後,光標相對於行首沒有任何,因此打印的結果爲第一行數據
row = cursor.fetchone()
print(row)

#4.關閉遊標
cursor.close()

#5.關閉鏈接
conn.close()

執行輸出結果:

blob.png


fetchmany()

import pymysql

# 1.鏈接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db='dbtest',
    charset='utf8')


# 2.建立遊標
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = 'select * from db2'
cursor.execute(sql)



# 獲取2條數據
rows = cursor.fetchmany(2)
print(rows)

# 4.關閉遊標

# rows = cursor.fetchall()
# print(rows)
cursor.close()

# 5.關閉鏈接
conn.close()

執行輸出:

blob.png

相關文章
相關標籤/搜索