python與MySQL數據庫的交互

python3中庫pymysql的使用

基本用法(連接SQL,執行SQL語句)

# 導入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數據庫地址”, user=“用戶名”,password=“密碼”,database=“數據庫名”,charset=“utf8”)
# 得到一個可以執行SQL語句的光標對象
cursor = conn.cursor()
# 定義要執行的SQL語句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 執行SQL語句
cursor.execute(sql)
# 關閉光標對象
cursor.close()
# 關閉數據庫連接
conn.close()

包裝成類代碼

class Mysql(object):
    def __init__(self):
        try:
            self.conn = pymysql.connect(
                host='127.0.0.1',
                port=3306,
                user='root',
                passwd='123456',
                db='test',
                charset='utf8'
            )
        except Exception as e:
            print(e)
        else:
            print('連接成功')
            self.cur = self.conn.cursor()

    def create_table(self):
        sql = 'create table testtb(id int, name varchar(10),age int)'
        res = self.cur.execute(sql)
        print(res)

    def close(self):
        self.cur.close()
        self.conn.close()

    def add(self):  # 增
        sql = 'insert into testtb values(1,"Tom",18),(2,"Jerry",16),(3,"Hank",24)'
        res = self.cur.execute(sql)
        if res:
            self.conn.commit()
        else:
            self.conn.rollback()
        print(res)

    def rem(self):  # 刪
        sql = 'delete from testtb where id=1'
        res = self.cur.execute(sql)
        if res:
            self.conn.commit()
        else:
            self.conn.rollback()
        print(res)

    def mod(self):  # 改
        sql = 'update testtb set name="Tom Ding" where id=2'
        res = self.cur.execute(sql)
        if res:
            self.conn.commit()
        else:
            self.conn.rollback()
        print(res)

    def show(self):  # 查
        sql = 'select * from testtb'
        self.cur.execute(sql)
        res = self.cur.fetchall()
        for i in res:
            print(i)

if __name__ == "__main__":
    mysql = Mysql()
    mysql.create_table()
    mysql.add()
    mysql.mod()
    mysql.rem()
    mysql.show()
    mysql.close()

其中的函數註解:

        # ret = self.cur.execute(sql)  # 返回內容的條數
        # print(ret)
        res = self.cur.fetchall()  # 返回元祖類型<class 'tuple'>
        # print(type(res))
        for i in res:
            print(i)
# 得到一個可以執行SQL語句並且將結果作爲字典返回的遊標
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

結果如圖(字典顯示):
在這裏插入圖片描述
原先的結果顯示(元祖類型):
在這裏插入圖片描述

“增刪改查”操作

“增”

注意字符串的拼接技巧

sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
# 執行SQL語句
cursor.execute(sql, [username, age])

有異常回滾事務

try:
    # 執行SQL語句
    cursor.execute(sql, [username, age])
    # 提交事務
    conn.commit()
except Exception as e:
	print(e)
    # 有異常,回滾事務
    conn.rollback()

批量插入數據

# 導入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數據庫地址”, user=“用戶名”,password=“密碼”,database=“數據庫名”,charset=“utf8”)
# 得到一個可以執行SQL語句的光標對象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
data = [("Alex", 18), ("Egon", 20), ("Yuan", 21)]
try:
    # 批量執行多條插入SQL語句
    cursor.executemany(sql, data)
    # 提交事務
    conn.commit()

except Exception as e:
    # 有異常,回滾事務
    conn.rollback()
cursor.close()
conn.close()

“刪”

sql = "DELETE FROM USER1 WHERE id=%s;"
try:
    cursor.execute(sql, [4])
    # 提交事務
    conn.commit()
except Exception as e:
    # 有異常,回滾事務
    conn.rollback()

“改”

# 修改數據的SQL語句
sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
username = "Alex"
age = 80
try:
    # 執行SQL語句
    cursor.execute(sql, [age, username])
    # 提交事務
    conn.commit()
except Exception as e:
    # 有異常,回滾事務
    conn.rollback()

“查”

查詢多條數據:

# 編寫sql 查詢語句  user 對應我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #執行sql語句  
    results = cur.fetchall()    #獲取查詢的所有記錄  
    print("id","name","password")  
    #遍歷結果  
    for row in results :  
        id = row[0]  
        name = row[1]  
        password = row[2]  
        print(id,name,password)  
except Exception as e:  
    raise e  
finally:  
    db.close()  #關閉連接  

查詢單條數據:

# 查詢數據的SQL語句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 執行SQL語句
cursor.execute(sql)
# 獲取單條查詢數據,取第一條
ret = cursor.fetchone()

指定數量:

cursor.fetchmany(3)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章