python3操作mysql數據庫

1.首先創建一個表用來測試

DROP TABLE IF EXISTS person;

CREATE TABLE `person` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255)  NOT NULL COMMENT '真實姓名',
 `height` decimal(8,2) NOT NULL COMMENT '身高',
 `weight` decimal(8,2)  NOT NULL COMMENT '體重',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert into person (name,height,weight) value ('李三',170,180);

2.pymysql模塊用來連接數據庫 連接參數含義

#創建數據庫連接
pymysql.Connect()參數說明
host(str):      MySQL服務器地址
port(int):      MySQL服務器端口號
user(str):      用戶名
passwd(str):    密碼
db(str):        數據庫名稱
charset(str):   連接編碼,存在中文的時候,連接需要添加charset='utf8',否則中文顯示亂碼。

connection對象支持的方法
cursor()        使用該連接創建並返回遊標
commit()        提交當前事務,不然無法保存新建或者修改的數據
rollback()      回滾當前事務
close()         關閉連接

cursor對象支持的方法
execute(op)     執行SQL,並返回受影響行數
fetchone()      取得結果集的下一行
fetchmany(size) 獲取結果集的下幾行
fetchall()      獲取結果集中的所有行
rowcount()      返回數據條數或影響行數
close()         關閉遊標對象

3.代碼

#! /bin/bash/python3.7

import pymysql.cursors


def test_connect():
    # 連接數據庫
    connect = pymysql.Connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='yunxin',
        charset='utf8'
    )

    # 獲取遊標
    cursor = connect.cursor()

    # 插入數據
    sql = "INSERT INTO person(name, height, weight) VALUES ( '%s',%.2f, %.2f )"
    data = ('趙四', 170, 120)
    cursor.execute(sql % data)
    connect.commit()
    print('成功插入', cursor.rowcount, '條數據')

    # 修改數據
    sql = "UPDATE person SET height = %.2f WHERE name = '%s' "
    data = (180, '趙四')
    cursor.execute(sql % data)
    connect.commit()
    print('成功修改', cursor.rowcount, '條數據')

    # 查詢數據
    sql = "SELECT name FROM person WHERE name = '%s' "
    data = ('趙四',)
    cursor.execute(sql % data)
    for row in cursor.fetchall():
        print(row)
    print('共查找出', cursor.rowcount, '條數據')

    # 刪除數據
    sql = "DELETE FROM person WHERE id = '%s'"
    data = ('1',)
    cursor.execute(sql % data)
    connect.commit()
    print('成功刪除', cursor.rowcount, '條數據')

    # 事務處理
    sql_1 = "UPDATE person SET height = height +1 WHERE name = '趙四' "
    sql_2 = "UPDATE person SET weight = weight +20 WHERE name  = '趙四' "

    try:
        cursor.execute(sql_1)
        cursor.execute(sql_2)
    except Exception as e:
        connect.rollback()  # 事務回滾
        print('事務處理失敗', e)
    else:
        connect.commit()  # 事務提交
        print('事務處理成功', cursor.rowcount)

        # 關閉連接
        cursor.close()
        connect.close()


if __name__ == "__main__":
    test_connect()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章