使用 pymysql 操作MySQL數(shù)據(jù)庫(kù)

安裝PyMySQL

PyMySQL是一個(gè)Python編寫的MySQL驅(qū)動(dòng)程序,讓我們可以用Python語(yǔ)言操作MySQL數(shù)據(jù)庫(kù)。

首先,使用pip安裝PyMySQL。

pip install PyMySQL

使用PyMySQL

簡(jiǎn)單使用

如果有JDBC等其他語(yǔ)言的數(shù)據(jù)庫(kù)學(xué)習(xí)經(jīng)驗(yàn)的話,使用PyMySQL非常簡(jiǎn)單。下面是一個(gè)完整的MySQL增刪查(沒(méi)有改)的例子。

import pymysql
import datetime

host = 'localhost'
username = 'root'
password = '12345678'
db_name = 'test'

create_table_sql = """\
CREATE TABLE fuck(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE ,
nickname VARCHAR(255) NOT NULL ,
birthday DATE
)
"""

insert_table_sql = """\
INSERT INTO fuck(username,nickname,birthday)
 VALUES('{username}','{nickname}','{birthday}')
"""

query_table_sql = """\
SELECT id,username,nickname,birthday
FROM fuck 
"""

delete_table_sql = """\
DELETE FROM fuck 
"""

drop_table_sql = """\
DROP TABLE fuck
"""

connection = pymysql.connect(host=host,
                             user=username,
                             password=password,
                             charset='utf8mb4',
                             db=db_name)

try:
    with connection.cursor() as cursor:
        print('--------------新建表--------------')
        cursor.execute(create_table_sql)
        connection.commit()

        print('--------------插入數(shù)據(jù)--------------')
        cursor.execute(
            insert_table_sql.format(username='yitian', nickname='易天', birthday=datetime.date.today()))
        cursor.execute(
            insert_table_sql.format(username='zhang3', nickname='張三', birthday=datetime.date.today()))
        cursor.execute(
            insert_table_sql.format(username='li4', nickname='李四', birthday=datetime.date.today()))
        cursor.execute(
            insert_table_sql.format(username='wang5', nickname='王五', birthday=datetime.date.today()))
        connection.commit()

        print('--------------查詢數(shù)據(jù)--------------')
        cursor.execute(query_table_sql)
        results = cursor.fetchall()
        print(f'id\tname\tnickname\tbirthday')
        for row in results:
            print(row[0], row[1], row[2], row[3], sep='\t')

        print('--------------清除數(shù)據(jù)--------------')
        cursor.execute(delete_table_sql)
        connection.commit()

        print('--------------刪除表--------------')
        cursor.execute(drop_table_sql)
        connection.commit()

finally:
    connection.close()

如果需要更詳細(xì)的資料,請(qǐng)查閱pymysql文檔或者其他資料。

防止SQL注入

在上面的例子中直接拼接字符串,這不是好辦法,因?yàn)榭赡艽嬖赟QL注入攻擊,更好的解決辦法是使用類庫(kù)提供的函數(shù)來(lái)傳參。所以上面的代碼也需要稍作修改。

首先,將帶參數(shù)的SQL語(yǔ)句改寫。

insert_table_sql = """\
INSERT INTO fuck(username,nickname,birthday)
 VALUES(%s,%s,%s)
"""

然后將相應(yīng)的執(zhí)行代碼也進(jìn)行修改,execute函數(shù)接受一個(gè)元組作為SQL參數(shù)。所以代碼改寫為這樣。

print('--------------插入數(shù)據(jù)--------------')
cursor.execute(insert_table_sql, ('yitian', '易天', datetime.date.today()))
cursor.execute(insert_table_sql, ('zhang3', '張三', datetime.date.today()))
cursor.execute(insert_table_sql, ('li4', '李四', datetime.date.today()))
cursor.execute(insert_table_sql, ('wang5', '王五', datetime.date.today()))
connection.commit()

這樣,SQL操作就更安全了。如果需要更詳細(xì)的文檔參考PyMySQL文檔吧。不過(guò)好像這些SQL數(shù)據(jù)庫(kù)的實(shí)現(xiàn)還不太一樣,PyMySQL的參數(shù)占位符使用%s這樣的C格式化符,而Python自帶的sqlite3模塊的占位符好像是?。因此在使用其他數(shù)據(jù)庫(kù)的時(shí)候還是仔細(xì)閱讀文檔吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容