1. 程式人生 > >【語法14】Python-mysql-connector驅動

【語法14】Python-mysql-connector驅動

MySQL 是最流行的關係型資料庫管理系統。

本章節我們為大家介紹使用 mysql-connector 來連線使用 MySQL, mysql-connector 是 MySQL 官方提供的驅動器。

我們可以使用 pip 命令來安裝 mysql-connector:

python3 -m pip install mysql-connector

使用以下程式碼測試 mysql-connector 是否安裝成功:

import mysql.connector

執行以上程式碼,如果沒有產生錯誤,表明安裝成功。

建立資料庫連線

import mysql.connector

mydb = mysql.connector.
connect( host="localhost", # 資料庫主機地址 user="root", # 資料庫使用者名稱 passwd="" # 資料庫密碼 ) print(mydb)
<mysql.connector.connection.MySQLConnection object at 0x0000019D2E6457F0>
#建立資料庫

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd =
'', ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE test2_db") mycursor.execute("SHOW DATABASES") for x in mycursor: print(x)
('information_schema',)
('mysql',)
('performance_schema',)
('sys',)
('test1_db',)
('test2_db',)
('test_db',)
#或者我們可以直接連線資料庫,如果資料庫不存在,會輸出錯誤資訊

import mysql.
connector mydb = mysql.connector.connect( host = 'localhost', user = 'root', passwd = '', database = 'test_db' )

建立資料表

# 建立資料表

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE test(name VARCHAR(255),url VARCHAR(255))")
#顯示資料表

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
    print(x)
('test',)
#設定主鍵

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE test ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

在這裡插入圖片描述

插入資料

#插入一條記錄
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

sql = "INSERT INTO test (name,url) VALUES (%s,%s)"
val = ("ECUST","Xu Huan")
mycursor.execute(sql,val)

mydb.commit()

print(mycursor.rowcount,'記錄插入成功')
1 記錄插入成功
#插入多條記錄
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

sql = "INSERT INTO test (name,url) VALUES (%s,%s)"
val = [("ECUST","Xu Huan"),
      ("MIT","Wang Yizhuo"),
      ("JHU","Nawukere"),
      ]
mycursor.executemany(sql,val)#使用executemany()插入多條記錄

mydb.commit()

print(mycursor.rowcount,'記錄插入成功')
3 記錄插入成功
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

sql = "INSERT INTO test (name,url) VALUES (%s,%s)"
val = [("PKU","Smith"),
      ]
mycursor.executemany(sql,val)

mydb.commit()

print('一條記錄已插入',mycursor.lastrowid)
一條記錄已插入 7

在這裡插入圖片描述

查詢資料

#查詢資料可以用SELECT語句

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test")

myresult = mycursor.fetchall() #fetchall()獲取所有記錄

for i in myresult:
    print(i)
('ECUST', 'Xu Huan', 1)
('ECUST', 'Xu Huan', 2)
('ECUST', 'Xu Huan', 3)
('MIT', 'Wang Yizhuo', 4)
('JHU', 'Nawukere', 5)
('PKU', 'Smith', 6)
('PKU', 'Smith', 7)
#也可以讀取指定的欄位資料

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT name,id FROM test")

myresult = mycursor.fetchall()

for i in myresult:
    print(i)
('ECUST', 1)
('ECUST', 2)
('ECUST', 3)
('MIT', 4)
('JHU', 5)
('PKU', 6)
('PKU', 7)
#如果只想讀取一條資料,可以使用fetchone()方法

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test")

myresult = mycursor.fetchone() 

print(myresult)
('ECUST', 'Xu Huan', 1)
#對讀取的資料有條件限制,可以使用where語句

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test WHERE name = 'ECUST'")

myresult = mycursor.fetchall() 

for i in myresult:
    print(i)
('ECUST', 'Xu Huan', 1)
('ECUST', 'Xu Huan', 2)
('ECUST', 'Xu Huan', 3)
#也可以使用萬用字元%

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test WHERE name LIKE '%K%'")

myresult = mycursor.fetchall() 

for i in myresult:
    print(i)
('PKU', 'Smith', 6)
('PKU', 'Smith', 7)
#為了防止資料庫查詢發生SQL注入的攻擊,可以使用%s佔位符轉義查詢的條件

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

sql = "SELECT * FROM test WHERE name = %s"
na = ('PKU',)

mycursor.execute(sql, na)

myresult = mycursor.fetchall() 

for i in myresult:
    print(i)
('PKU', 'Smith', 6)
('PKU', 'Smith', 7)
#排序

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test ORDER BY url")

myresult = mycursor.fetchall() 

for i in myresult:
    print(i)
('JHU', 'Nawukere', 5)
('PKU', 'Smith', 6)
('PKU', 'Smith', 7)
('MIT', 'Wang Yizhuo', 4)
('ECUST', 'Xu Huan', 1)
('ECUST', 'Xu Huan', 2)
('ECUST', 'Xu Huan', 3)
#對資料基於某屬性降序排序

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test ORDER BY name DESC")

myresult = mycursor.fetchall() 

for i in myresult:
    print(i)
('PKU', 'Smith', 6)
('PKU', 'Smith', 7)
('MIT', 'Wang Yizhuo', 4)
('JHU', 'Nawukere', 5)
('ECUST', 'Xu Huan', 1)
('ECUST', 'Xu Huan', 2)
('ECUST', 'Xu Huan', 3)
#讀取指定數量條資料
#限制讀取資料起始資料
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM test LIMIT 4 OFFSET 2")
#用LIMIT語句指定查詢資料量
#用OFFSET語句限制起始位置

myresult = mycursor.fetchall() 

for i in myresult:
    print(i)
('ECUST', 'Xu Huan', 3)
('MIT', 'Wang Yizhuo', 4)
('JHU', 'Nawukere', 5)
('PKU', 'Smith', 6)

刪除記錄

#使用DELETE FROM語句刪除記錄
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

mycursor.execute("DELETE FROM test WHERE name LIKE '%K%'")

mydb.commit()
 
print(mycursor.rowcount, " 條記錄刪除")
2  條記錄刪除
#為了防止資料庫查詢發生 SQL 注入的攻擊,我們可以使用 %s 佔位符來轉義刪除語句的條件

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

sql = "DELETE FROM test WHERE name = %s"
na = ("ECUST",)

mycursor.execute(sql,na)

mydb.commit()
 
print(mycursor.rowcount, " 條記錄刪除")
3  條記錄刪除

更新表資料

import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()


sql = "UPDATE test SET name = 'princeton' WHERE name = 'JHU'"
 
mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount,'條記錄被修改')
2 條記錄被修改
#為了防止資料庫查詢發生 SQL 注入的攻擊,我們可以使用 %s 佔位符來轉義更新語句的條件
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()


sql = "UPDATE test SET name = %s WHERE name = %s"
na = ('JHU','princeton')
 
mycursor.execute(sql,na)

mydb.commit()

print(mycursor.rowcount,'條記錄被修改')
2 條記錄被修改

刪除表

#使用DROP TABLE語句刪除表,使用IF EXISTS關鍵字判斷表是否尊在
import mysql.connector

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '',
    database = 'test_db',
)

mycursor = mydb.cursor()

sql = 'DROP TABLE IF EXISTS test'

mycursor.execute(sql)

在這裡插入圖片描述