天天看點

MySQL學習9:資料庫子產品pymysql的使用

pymysql的安裝

pip install pymysql      

使用Python DB API通路資料庫流程

MySQL學習9:資料庫子產品pymysql的使用

讀取資料

關鍵詞:

fetchone():讀取一條資料(一條條出棧),每個資料以元組形式傳回。

fetchall():讀取所有資料,所有資料以元組套元組的形式傳回。

fetmany(資料個數):讀取指定條資料,括号内填資料個數。

查詢代碼示例

import pymysql

def main():
    # 建立Connection連接配接
    conn = pymysql.connect(host="localhost", port=3306, user="root", password="這裡是自己資料庫的密碼", database="myfirst")
    # 獲得Cursor對象
    csl = conn.cursor()
    # 執行sql語句
    count = csl.execute("select * from heros ")
    print("查詢到%d資料:" % count)

    for i in range(count):
        result = csl.fetchone()
        print(result)

    csl.close()
    conn.close()


if __name__ == '__main__':
    main()      

增加、删除、修改資料

sql語句不變,但增加、删除、修改後需要進行送出更新:

conn.commit()      

撤回操作:

conn.rollback()      

注:寫sql語句時,一對雙引号"“容易産生誤判,最外層的雙引号可以改為連續三個”"" “”"。

sql注入

原理:當我們寫sql語句時,若采用字元串拼接的方式将使用者的輸入拼接成sql語句,這個時候就存在sql注入漏洞。

下面這段程式将說明如何進行一個簡單的sql注入。

import pymysql

def main():
    # 建立Connection連接配接
    conn = pymysql.connect(host="localhost", port=3306, user="root", password="zxy100300", database="myfirst")
    # 獲得Cursor對象
    csl = conn.cursor()
    print("請輸入需要查找的名字:")
    find_name = input()
    sql = 'select * from heros where name="%s"' % find_name
    # 執行sql語句
    count = csl.execute(sql)
    print("查詢到%d條資料:" % count)

    for i in range(count):
        result = csl.fetchone()
        print(result)

    csl.close()
    conn.close()

    #輸入注入語句" or 1=1 or"
if __name__ == '__main__':
    main()      

運作程式,使用者可以正常輸入人名進行查詢。

MySQL學習9:資料庫子產品pymysql的使用

然而,如果輸入漏洞注入指令 “or 1=1 or”

将會把資料庫中所有的資料幹出來(我這裡總共隻有兩條資料)

MySQL學習9:資料庫子產品pymysql的使用

原因分析:

實作注入的程式語句是這條:

sql = 'select * from heros where name="%s"' %      

其中,字元串由一對雙引号進行包裹。

是以,"or 1=1 or"中,一前一後兩個引号實作各自配對,中間的1=1永遠成立,是以傳回值為1。

将其代入,就會得到這條查詢指令:

select * from heros where name="" or 1=1 or "";      

等價于

select * from heros where true;      

條件始終成立,是以所有的資料全部被暴露出來。

這,就實作了一次sql注入。

防sql注入

sql注入很難從根本上防止,是以,防止sql注入就需要對資料進行過濾,防止惡意資料的輸入。

下面就是用元組對資料進行包裹,用execute本身的函數機制防止注入指令。

import pymysql


def main():
    # 建立Connection連接配接
    conn = pymysql.connect(host="localhost", port=3306, user="root", password="zxy100300", database="myfirst")
    # 獲得Cursor對象
    csl = conn.cursor()
    print("請輸入需要查找的名字:")
    find_name = input()
    params = [find_name]
    # 執行sql語句
    count = csl.execute('select * from heros where name=%s', params)
    print("查詢到%d條資料:" % count)

    for i in range(count):
        result = csl.fetchone()
        print(result)

    csl.close()
    conn.close()

    # 輸入注入語句"or 1=1 or"


if __name__ == '__main__':
    main()      

效果:

MySQL學習9:資料庫子產品pymysql的使用