python propresql mysql_Python中操作mysql的pymysql模块详解
PyMySQL是一個Python編寫的MySQL驅(qū)動程序,讓我們可以用Python語言操作MySQL數(shù)據(jù)庫。
首先,使用pip安裝PyMySQL。
pip install PyMySQL
使用PyMySQL
簡單使用
如果有JDBC等其他語言的數(shù)據(jù)庫學(xué)習(xí)經(jīng)驗的話,使用PyMySQL非常簡單。下面是一個完整的MySQL增刪查(沒有改)的例子。
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ì)的資料,請查閱pymysql文檔或者其他資料。
防止SQL注入
在上面的例子中直接拼接字符串,這不是好辦法,因為可能存在SQL注入攻擊,更好的解決辦法是使用類庫提供的函數(shù)來傳參。所以上面的代碼也需要稍作修改。
首先,將帶參數(shù)的SQL語句改寫。
insert_table_sql = """\
INSERT INTO fuck(username,nickname,birthday)
VALUES(%s,%s,%s)
"""
然后將相應(yīng)的執(zhí)行代碼也進行修改,execute函數(shù)接受一個元組作為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文檔吧。不過好像這些SQL數(shù)據(jù)庫的實現(xiàn)還不太一樣,PyMySQL的參數(shù)占位符使用%s這樣的C格式化符,而Python自帶的sqlite3模塊的占位符好像是?。因此在使用其他數(shù)據(jù)庫的時候還是仔細(xì)閱讀文檔吧。
總結(jié)
以上是生活随笔為你收集整理的python propresql mysql_Python中操作mysql的pymysql模块详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pyqt漂亮gui界面模板_一种基于模板
- 下一篇: python解析xml文件element