Python3入門(十三)——鏈接數據庫

以Mysql爲例:python

 

要操做關係數據庫,首先須要鏈接到數據庫,一個數據庫鏈接稱爲Connection; 鏈接到數據庫後,須要打開遊標,稱之爲Cursor,經過Cursor執行SQL語句,而後,得到執行結果。

 

 

 

1。安裝驅動mysql

$ pip install mysql-connector-python --allow-external mysql-connector-python

或者嘗試:sql

$ pip install mysql-connector

安裝過程以下:數據庫

2.使用代碼鏈接fetch

  

# 導入驅動
import mysql.connector

# 鏈接信息
conn = mysql.connector.connect(user="root", password="root", database="sakila")
# 獲取遊標
cursor = conn.cursor()
# 運行查詢
cursor.execute("SELECT * FROM actor WHERE first_name = %s", ("NICK",))
# 獲取結果
values = cursor.fetchall()
print(values)
# 關閉鏈接
cursor.close()
conn.close()

  注意佔位符的使用spa

相關文章
相關標籤/搜索