1. 程式人生 > >PyMySQL學習筆記

PyMySQL學習筆記

一些常用函式及解釋

db = pymysql.connect('host','user','password','database') # 連線資料庫

cursor = db.cursor() # 建立遊標物件

cursor.execute(sql) # 執行sql語句sql為sql語句

data = cursor.fetchone() # 獲取單條資料(具體用法見下面示例)

data_list = fetchall() # 接收全部的返回結果行

db.commit() # 提交到資料庫執行

db.rollback() # 發生錯誤回滾

db.close() # 關閉連線

主要操作是通過sql語句遞交給execute()函式執行

以下是一些常用方法的例子

資料庫建立表操作程式碼示例

import pymysql

# 連結資料庫
db = pymysql.connect("yourhost", "yourname", "yourpassword", "yourdatabase")

# 建立遊標物件
cursor = db.cursor()

# 使用execute()方法執行SQL,如果表存在則刪除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# SQL語句建立表
sql = """
        CREATE TABLE EMPLOYEE (
        FIRST_NAME CHAR(20) NOT NULL,
        LAST_NAME CHAR(20),
        AGE INT,
        SEX CHAR(1),
        INCOME FLOAT )
        """
cursor.execute(sql)

# 關閉資料庫連線
db.close()

資料庫插入操作程式碼示例

import pymysql

config = {
    "host":"yourhost",
    "user":"yourname",
    "password":"yourpassword",
    "database":"yourdatabase"
}

db = pymysql.connect(**config)

cursor = db.cursor()
F_name = 'Dawei'
L_name = 'Wang'
age = 20
sex = 'M'
income = 2000

# 注意 %s 外加引號,作為字元,否者mysql會認為是一個column
sql = "INSERT INTO EMPLOYEE (FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) VALUES \
       ('%s', '%s',  '%s',  '%s',  '%s')" %\
       (F_name, L_name, age, sex, income)
try:
    # 執行SQL語句
    cursor.execute(sql)
    # 提交到資料庫執行,為了及時跟進資料庫這句最好加上
    db.commit()
except:
    # 如果發生錯誤則回滾
    db.rollback()

db.close()

資料庫查詢操作程式碼示例

import pymysql

config = {
    "host":"yourhost",
    "user":"yourname",
    "password":"yourpassword",
    "database":"yourdatabase"
}

db = pymysql.connect(**config)

cursor = db.cursor()

# SQL 查詢語句
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > %s" % (1000)

try:
    # 執行語句
    cursor.execute(sql)
    # 獲取所有列表記錄
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        # 列印結果
        print("fname = %s, lname = %s, age = %s, sex = %s, income = %s" % \
             (fname, lname, age, sex, income ))
except:
    print("Error: unable to fetch data")

db.close()

資料庫更新操作程式碼示例

import pymysql

config = {
    "host":"yourhost",
    "user":"yourname",
    "password":"yourpassword",
    "database":"yourdatabase"
}

db = pymysql.connect(**config)

cursor = db.cursor()

# SQL 更新語句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
    # 執行SQL語句
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close()

資料庫刪除操作程式碼示例

import pymysql

config = {
    "host":"yourhost",
    "user":"yourname",
    "password":"yourpassword",
    "database":"yourdatabase"
}

db = pymysql.connect(**config)

cursor = db.cursor()

# SQL 刪除語句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)

try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close()