吳裕雄--天生天然 PYTHON3開發學習:MySQL - mysql-connector 驅動

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",       # 數據庫主機地址
  user="yourusername",    # 數據庫用戶名
  passwd="yourpassword"   # 數據庫密碼
)
 
print(mydb)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456"
)
 
mycursor = mydb.cursor()
 
mycursor.execute("CREATE DATABASE runoob_db")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456"
)
 
mycursor = mydb.cursor()
 
mycursor.execute("SHOW DATABASES")
 
for x in mycursor:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SHOW TABLES")
 
for x in mycursor:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("RUNOOB", "https://www.runoob.com")
mycursor.execute(sql, val)
 
mydb.commit()    # 數據表內容有更新,必須使用到該語句
 
print(mycursor.rowcount, "記錄插入成功。")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
  ('Google', 'https://www.google.com'),
  ('Github', 'https://www.github.com'),
  ('Taobao', 'https://www.taobao.com'),
  ('stackoverflow', 'https://www.stackoverflow.com/')
]
 
mycursor.executemany(sql, val)
 
mydb.commit()    # 數據表內容有更新,必須使用到該語句
 
print(mycursor.rowcount, "記錄插入成功。")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("Zhihu", "https://www.zhihu.com")
mycursor.execute(sql, val)
 
mydb.commit()
 
print("1 條記錄已插入, ID:", mycursor.lastrowid)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites")
 
myresult = mycursor.fetchall()     # fetchall() 獲取全部記錄
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT name, url FROM sites")
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites")
 
myresult = mycursor.fetchone()
 
print(myresult)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE name ='RUNOOB'"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE url LIKE '%oo%'"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE name = %s"
na = ("RUNOOB", )
 
mycursor.execute(sql, na)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites ORDER BY name"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites ORDER BY name DESC"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites LIMIT 3")
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
Python 3 教程
Python3 教程
Python3 環境搭建
Python3 基礎語法
Python3 基本數據類型
Python3 解釋器
Python3 註釋
Python3 運算符
Python3 數字(Number)
Python3 字符串
Python3 列表
Python3 元組
Python3 字典
Python3 集合
Python3 編程第一步
Python3 條件控制
Python3 循環語句
Python3 迭代器與生成器
Python3 函數
Python3 數據結構
Python3 模塊
Python3 輸入和輸出
Python3 File
Python3 OS
Python3 錯誤和異常
Python3 面向對象
Python3 標準庫概覽
Python3 實例
Python 測驗

Python3 高級教程
Python3 正則表達式
Python3 CGI編程
Python3 MySQL(mysql-connector)
Python3 MySQL(PyMySQL)
Python3 網絡編程
Python3 SMTP發送郵件
Python3 多線程
Python3 XML 解析
Python3 JSON
Python3 日期和時間
Python3 內置函數
Python MongoDB
Python uWSGI 安裝配置
 Python3 CGI編程 Python3 MySQL 數據庫鏈接 – PyMySQL 驅動 
Python MySQL - mysql-connector 驅動
MySQL 是最流行的關係型數據庫管理系統,若是你不不熟悉 MySQL,能夠閱讀咱們的 MySQL 教程。

本章節咱們爲你們介紹使用 mysql-connector 來鏈接使用 MySQL, mysql-connector 是 MySQL 官方提供的驅動器。

咱們能夠使用 pip 命令來安裝 mysql-connector:

python -m pip install mysql-connector
使用如下代碼測試 mysql-connector 是否安裝成功:

demo_mysql_test.py:
import mysql.connector
執行以上代碼,若是沒有產生錯誤,代表安裝成功。

建立數據庫鏈接
能夠使用如下代碼來鏈接數據庫:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",       # 數據庫主機地址
  user="yourusername",    # 數據庫用戶名
  passwd="yourpassword"   # 數據庫密碼
)
 
print(mydb)
建立數據庫
建立數據庫使用 "CREATE DATABASE" 語句,如下建立一個名爲 runoob_db 的數據庫:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456"
)
 
mycursor = mydb.cursor()
 
mycursor.execute("CREATE DATABASE runoob_db")
建立數據庫前咱們也能夠使用 "SHOW DATABASES" 語句來查看數據庫是否存在:

demo_mysql_test.py:
輸出全部數據庫列表:

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456"
)
 
mycursor = mydb.cursor()
 
mycursor.execute("SHOW DATABASES")
 
for x in mycursor:
  print(x)
或者咱們能夠直接鏈接數據庫,若是數據庫不存在,會輸出錯誤信息:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
建立數據表
建立數據表使用 "CREATE TABLE" 語句,建立數據表前,須要確保數據庫已存在,如下建立一個名爲 sites 的數據表:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
執行成功後,咱們能夠看到數據庫建立的數據表 sites,字段爲 name 和 url。


咱們也能夠使用 "SHOW TABLES" 語句來查看數據表是否已存在:
demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SHOW TABLES")
 
for x in mycursor:
  print(x)
主鍵設置
建立表的時候咱們通常都會設置一個主鍵(PRIMARY KEY),咱們能夠使用 "INT AUTO_INCREMENT PRIMARY KEY" 語句來建立一個主鍵,主鍵起始值爲 1,逐步遞增。

若是咱們的表已經建立,咱們須要使用 ALTER TABLE 來給表添加主鍵:

demo_mysql_test.py:
給 sites 表添加主鍵。

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
若是你還未建立 sites 表,能夠直接使用如下代碼建立。

demo_mysql_test.py:
給表建立主鍵。

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")
插入數據
插入數據使用 "INSERT INTO" 語句:

demo_mysql_test.py:
向 sites 表插入一條記錄。

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("RUNOOB", "https://www.runoob.com")
mycursor.execute(sql, val)
 
mydb.commit()    # 數據表內容有更新,必須使用到該語句
 
print(mycursor.rowcount, "記錄插入成功。")
執行代碼,輸出結果爲:

1 記錄插入成功
批量插入
批量插入使用 executemany() 方法,該方法的第二個參數是一個元組列表,包含了咱們要插入的數據:

demo_mysql_test.py:
向 sites 表插入多條記錄。

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
  ('Google', 'https://www.google.com'),
  ('Github', 'https://www.github.com'),
  ('Taobao', 'https://www.taobao.com'),
  ('stackoverflow', 'https://www.stackoverflow.com/')
]
 
mycursor.executemany(sql, val)
 
mydb.commit()    # 數據表內容有更新,必須使用到該語句
 
print(mycursor.rowcount, "記錄插入成功。")
執行代碼,輸出結果爲:

4 記錄插入成功。
執行以上代碼後,咱們能夠看看數據表的記錄:



若是咱們想在數據記錄插入後,獲取該記錄的 ID ,能夠使用如下代碼:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("Zhihu", "https://www.zhihu.com")
mycursor.execute(sql, val)
 
mydb.commit()
 
print("1 條記錄已插入, ID:", mycursor.lastrowid)
執行代碼,輸出結果爲:

1 條記錄已插入, ID: 6
查詢數據
查詢數據使用 SELECT 語句:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites")
 
myresult = mycursor.fetchall()     # fetchall() 獲取全部記錄
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
(4, 'Taobao', 'https://www.taobao.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(6, 'Zhihu', 'https://www.zhihu.com')
也能夠讀取指定的字段數據:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT name, url FROM sites")
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

('RUNOOB', 'https://www.runoob.com')
('Google', 'https://www.google.com')
('Github', 'https://www.github.com')
('Taobao', 'https://www.taobao.com')
('stackoverflow', 'https://www.stackoverflow.com/')
('Zhihu', 'https://www.zhihu.com')
若是咱們只想讀取一條數據,能夠使用 fetchone() 方法:

demo_mysql_test.py:
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites")
 
myresult = mycursor.fetchone()
 
print(myresult)
執行代碼,輸出結果爲:

(1, 'RUNOOB', 'https://www.runoob.com')
where 條件語句
若是咱們要讀取指定條件的數據,能夠使用 where 語句:

demo_mysql_test.py
讀取 name 字段爲 RUNOOB 的記錄:

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE name ='RUNOOB'"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

(1, 'RUNOOB', 'https://www.runoob.com')
也能夠使用通配符 %:

demo_mysql_test.py
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE url LIKE '%oo%'"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
爲了防止數據庫查詢發生 SQL 注入的攻擊,咱們能夠使用 %s 佔位符來轉義查詢的條件:

demo_mysql_test.py
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE name = %s"
na = ("RUNOOB", )
 
mycursor.execute(sql, na)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
排序
查詢結果排序能夠使用 ORDER BY 語句,默認的排序方式爲升序,關鍵字爲 ASC,若是要設置降序排序,能夠設置關鍵字 DESC。

demo_mysql_test.py
按 name 字段字母的升序排序:

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites ORDER BY name"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

(3, 'Github', 'https://www.github.com')
(2, 'Google', 'https://www.google.com')
(1, 'RUNOOB', 'https://www.runoob.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(4, 'Taobao', 'https://www.taobao.com')
(6, 'Zhihu', 'https://www.zhihu.com')
降序排序實例:

demo_mysql_test.py
按 name 字段字母的降序排序:

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites ORDER BY name DESC"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

(6, 'Zhihu', 'https://www.zhihu.com')
(4, 'Taobao', 'https://www.taobao.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
Limit
若是咱們要設置查詢的數據量,能夠經過 "LIMIT" 語句來指定

demo_mysql_test.py
讀取前 3 條記錄:

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites LIMIT 3")
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
執行代碼,輸出結果爲:

(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
也能夠指定起始位置,使用的關鍵字是 OFFSET:

demo_mysql_test.py
從第二條開始讀取前 3 條記錄:

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM sites LIMIT 3 OFFSET 1")  # 0 爲 第一條,1 爲第二條,以此類推
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "DELETE FROM sites WHERE name = 'stackoverflow'"
 
mycursor.execute(sql)
 
mydb.commit()
 
print(mycursor.rowcount, " 條記錄刪除")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "DELETE FROM sites WHERE name = %s"
na = ("stackoverflow", )
 
mycursor.execute(sql, na)
 
mydb.commit()
 
print(mycursor.rowcount, " 條記錄刪除")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'"
 
mycursor.execute(sql)
 
mydb.commit()
 
print(mycursor.rowcount, " 條記錄被修改")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "UPDATE sites SET name = %s WHERE name = %s"
val = ("Zhihu", "ZH")
 
mycursor.execute(sql, val)
 
mydb.commit()
 
print(mycursor.rowcount, " 條記錄被修改")
import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "DROP TABLE IF EXISTS sites"  # 刪除數據表 sites
 
mycursor.execute(sql)
相關文章
相關標籤/搜索