本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于我偶像龜叔,作者我偶像龜叔
MYSQL是目前應用最廣泛、普及度最高的開源關系型資料庫,體積小、速度快、總體擁有成本低,開源是使得它廣為普及的主要原因,
今天將 Python 與 Mysql 的結合,兩者進行互動,一起來學習吧!
1、創建資料庫連接
import mysql.connector
config = {
'host': 'localhost',
'port': '3306',
'user': 'root',
'password': '',
'database': 'python'
}
con = mysql.connector.connect(**config)
cursor = con.cursor() #游標,用于執行sql陳述句
2、創建資料表
create_table_sql = "CREATE TABLE `browser` (" \
"`id` INT AUTO_INCREMENT PRIMARY KEY COMMENT 'id', " \
"`name` VARCHAR(128) COMMENT '名字', " \
"`url` VARCHAR(255) COMMENT '官網'" \
")"
cursor.execute(create_table_sql)
3、創建索引
_index1 = "ALTER TABLE `browser` ADD UNIQUE INDEX name(name)" #唯一索引
_index2 = "CREATE INDEX url ON `browser`(url)" #普通索引
for sql in [_index1, _index2]:
cursor.execute(sql)
創建表結構和添加欄位索引個人建議客戶端手動操作,一行一行代碼操作效率實在太低,這邊公眾號回復"mysql"獲取相關資源,
4、資料增刪查改
#插入單條資料
insert_sql = "INSERT INTO `browser`(name, url) VALUES (%s, %s)"
values = ('Chrome', "http://www.google.cn/chrome/")
cursor.execute(insert_sql, values)
#插入多條資料
values = [
('Chrome', "http://www.google.cn/chrome/"),
('Firefox', "http://www.firefox.com/"),
('Safari2', "https://www.apple.com.cn/safari/")
]
cursor.executemany(insert_sql, values)
#查詢資料
select_sql = "SELECT * FROM `browser`"
cursor.execute(select_sql)
print(cursor.fetchone()) #獲取單條資料
print(cursor.fetchall()) #獲取全部資料
#更新資料
update_sql = "UPDATE `browser` SET `url`='http://www.firefox.com.cn' WHERE `name`='Firefox';"
cursor.execute(update_sql)
#洗掉資料
delete_sql = "DELETE FROM `browser` WHERE `name` = %s"
cursor.execute(delete_sql, ['Safari'])
5、關于抵御注入攻擊
由于Sql陳述句是解釋性語言,所以在拼接Sql陳述句的時候,容易被注入惡意的Sql陳述句,
sql陳述句編譯程序中,關鍵字被決議過,所以向編譯后的sql陳述句傳入引數,都被當字串處理,資料庫不會決議其中注入的sql陳述句,
6、事務控制與例外處理
try:
con.start_transaction()
cursor = con.cursor()
delete_sql = "DELETE FROM `browser` WHERE `name` = %s"
cursor.execute(delete_sql, ['Firefox'])
except Exception as e:
con.rollback() #回滾
else:
con.commit() #提交
7、實作資料庫連接池
如果每次進行操作前都去做連接請求,是非常消耗資源的,尤為考慮到并發問題的時候,
資料庫連接池預先創建出一些資料庫連接,然后快取起來,避免出現重復創建和銷毀連接付出昂貴的代價,很好的解決這個問題,
import mysql.connector.pooling
config = {...}
pool = mysql.connector.pooling.MySQLConnectionPool(
**config,
pool_size=10
)
con_pool = pool.get_connection()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/195933.html
標籤:Python
