Python3使用PyMySQL操做數據庫

1. 安裝PyMySQL

pip install PyMySQL

關於PyMySQL的詳細內容能夠查看官方文檔  Githubpython

2. 建立表

在某個數據庫內,使用如下指令建表mysql

CREATE TABLE `users` 
(
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255)  NOT NULL,
  `password` varchar(255)  NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8 COLLATE=utf8_bin

3. 使用PyMySQL執行增刪改查

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2019-1-7 15:43
# @Author  : Z.C.Wang
# @Email   : iwangzhengchao@gmail.com
# @File    : PyConnectionMySQL.py
# @Software: PyCharm Community Edition
"""
Description :
pymysql.Connect()參數說明
host(str):      MySQL服務器地址
port(int):      MySQL服務器端口號
user(str):      用戶名
passwd(str):    密碼
db(str):        數據庫名稱
charset(str):   鏈接編碼

connection對象支持的方法
cursor()        使用該鏈接建立並返回遊標
commit()        提交當前事務
rollback()      回滾當前事務
close()         關閉鏈接

cursor對象支持的方法
execute(sql, args)     執行一個數據庫的查詢命令
fetchone()      取得結果集的下一行
fetchmany(size) 獲取結果集的下幾行
fetchall()      獲取結果集中的全部行
close()         關閉遊標對象
"""
import pymysql

# 鏈接數據庫
connection = pymysql.connect(host='localhost', user='root', password='root',
                             db='test', charset='utf8')

if connection.open:
    print('the connection is open...')

# 清空users表
cursor = connection.cursor()
cursor.execute("truncate table users")
connection.commit()

# (1)批量插入
record = []
for i in range(10):
    email = "mail_" + str(i) + "@qq.com"
    password = "xxx_" + str(i)
    record.append((email, password))

try:
    sql = "insert into users (email, password) values (%s, %s)"
    rows = cursor.executemany(sql, record)
    connection.commit()
    print("insert success. affected rows : %d" % rows)
except:
    print("insert ERROR.")
    connection.rollback()

# (2)刪除記錄
try:
    sql = "delete from users where id=1"
    rows = cursor.execute(sql)
    connection.commit()
    print("delete success. affected rows : %d" % rows)
except:
    print("delete ERROR.")
    connection.rollback()

# (3)修改記錄
try:
    sql = "update users set password='yyy' where id=5"
    rows = cursor.execute(sql)
    connection.commit()
    print("update success. affected rows : %d" % rows)
except:
    print("update ERROR.")
    connection.rollback()

# (4)查詢記錄
try:
    sql = 'select * from users'
    count = cursor.execute(sql)
    print("number of record in users: %d" % count)
    result = cursor.fetchall()
    for row in result:
        print(row)
    connection.commit()
except:
    print("query ERROR.")
    connection.rollback()

# 關閉鏈接
cursor.close()
connection.close()
print("connection close.")

運行結果:git

D:\Python3.6_2\python.exe E:/PycharmProjects/PyConnectionMySQL/PyConnectionMySQL.py
the connection is open...
insert success. affected rows : 10
delete success. affected rows : 1
update success. affected rows : 1
number of record in users: 9
(2, 'mail_1@qq.com', 'xxx_1')
(3, 'mail_2@qq.com', 'xxx_2')
(4, 'mail_3@qq.com', 'xxx_3')
(5, 'mail_4@qq.com', 'yyy')
(6, 'mail_5@qq.com', 'xxx_5')
(7, 'mail_6@qq.com', 'xxx_6')
(8, 'mail_7@qq.com', 'xxx_7')
(9, 'mail_8@qq.com', 'xxx_8')
(10, 'mail_9@qq.com', 'xxx_9')
connection close.

Process finished with exit code 0
相關文章
相關標籤/搜索