Python鏈接MySQL數據庫之pymysql模塊使用

 

Python3鏈接MySQL

本文介紹Python3鏈接MySQL的第三方庫--PyMySQL的基本使用。html

PyMySQL介紹

PyMySQL 是在 Python3.x 版本中用於鏈接 MySQL 服務器的一個庫,Python2中則使用mysqldb。python

Django中也可使用PyMySQL鏈接MySQL數據庫。mysql

PyMySQL安裝

#終端中安裝pymysql
pip install pymysql
python3.6 使用 pymysql 鏈接 Mysql 數據庫及 簡單的增刪改查操做
進入 cmd  輸入  pip install pymysql  
回車等待安裝完成;
安裝完成後出現如圖相關信息,表示安裝成功。

鏈接數據庫

MySQL 鏈接


使用mysql二進制方式鏈接

您可使用MySQL二進制方式進入到mysql命令提示符下來鏈接MySQL數據庫。sql

實例

如下是從命令行中鏈接mysql服務器的簡單實例:數據庫

#[root@host]# mysql -u root -p
#Enter password:******

 

在登陸成功後會出現 mysql> 命令提示窗口,你能夠在上面執行任何 SQL 語句。服務器

以上命令執行後,登陸成功輸出結果以下:post

#Welcome to the MySQL monitor.  Commands end with ; or \g.
#Your MySQL connection id is 2854760 to server version: 5.0.9

#Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

 

在以上實例中,咱們使用了root用戶登陸到mysql服務器,固然你也可使用其餘mysql用戶登陸。測試

若是用戶權限足夠,任何用戶均可以在mysql的命令提示窗口中進行SQL操做。fetch

退出 mysql> 命令提示窗口可使用 exit 命令,以下所示:flex

mysql> exit
Bye

 

建立數據庫

 

#-- 建立一個名爲day59的數據庫

cerate database day59;
# -- 使用day59數據庫
 use day59;
#-- 建立一個userinfo表
 create table userinfo (id int auto_increment primary key,name varchar(10) not null, pwd varchar(18) not null );

#-- 查看錶結構是否正確
desc userinfo;
#-- 添加3條測試數據 insert into userinfo (name, pwd) values ("alex", "alex3714"),("xiaohei", "123456"),("yimi", "654321"); #-- 查看數據 select * from userinfo; #-- 根據特定的用戶名和密碼從數據庫中檢索 select * from userinfo where name="alex" and pwd="alex3714";
 
   
  
 

 

注意事項

在進行本文如下內容以前須要注意:

  • 你有一個MySQL數據庫,而且已經啓動。
  • 你有能夠鏈接該數據庫的用戶名和密碼
  • 你有一個有權限操做的database

基本使用

複製代碼
# 導入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()
複製代碼
#注意:harset="utf8",中間沒有空格,由於mySql不支持

 

 

返回字典格式數據:

複製代碼
# 導入pymysql模塊
import pymysql
# 鏈接database
conn = pymysql.connect(host=「你的數據庫地址」, user=「用戶名」,password=「密碼」,database=「數據庫名」,charset=「utf8」)
# 獲得一個能夠執行SQL語句而且將結果做爲字典返回的遊標
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定義要執行的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()
複製代碼

 

注意:

charset=「utf8」,編碼不要寫成"utf-8"

數據庫版登陸

 
 

 

增刪改查操做

 

複製代碼
# 導入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);"
username = "Alex"
age = 18
# 執行SQL語句
cursor.execute(sql, [username, age])
# 提交事務
conn.commit()
cursor.close()
conn.close()
複製代碼
複製代碼

mysql端:

 

複製代碼

  

插入數據失敗回滾

複製代碼
# 導入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);"
username = "Alex"
age = 18
try:
    # 執行SQL語句
    cursor.execute(sql, [username, age])
    # 提交事務
    conn.commit()
except Exception as e:
    # 有異常,回滾事務
    conn.rollback()
cursor.close()
conn.close()
複製代碼

 

獲取插入數據的ID(關聯操做時會用到)

複製代碼
# 導入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);"
username = "Alex"
age = 18
try:
    # 執行SQL語句
    cursor.execute(sql, [username, age])
    # 提交事務
    conn.commit()
    # 提交以後,獲取剛插入的數據的ID
    last_id = cursor.lastrowid
except Exception as e:
    # 有異常,回滾事務
    conn.rollback()
cursor.close()
conn.close()

 

複製代碼

 

批量執行

複製代碼
# 導入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()
複製代碼
複製代碼

因爲數據庫的編碼格式不同因此出現亂碼:

建立數據庫的時候指定編碼須要:

建立列表的時候也要指定一下,避免亂碼:

 

複製代碼

 

 

複製代碼
# 導入pymysql模塊
import pymysql
# 鏈接database
conn = pymysql.connect(host=「你的數據庫地址」, user=「用戶名」,password=「密碼」,database=「數據庫名」,charset=「utf8」)
# 獲得一個能夠執行SQL語句的光標對象
cursor = conn.cursor()
sql = "DELETE FROM USER1 WHERE id=%s;"
try:
    cursor.execute(sql, [4])
    # 提交事務
    conn.commit()
except Exception as e:
    # 有異常,回滾事務
    conn.rollback()
cursor.close()
conn.close()

複製代碼

 

複製代碼
# 導入pymysql模塊
import pymysql
# 鏈接database
conn = pymysql.connect(host=「你的數據庫地址」, user=「用戶名」,password=「密碼」,database=「數據庫名」,charset=「utf8」)
# 獲得一個能夠執行SQL語句的光標對象
cursor = conn.cursor()
# 修改數據的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()
cursor.close()
conn.close()

複製代碼

 

複製代碼
#查詢操做

import pymysql  #導入 pymysql  
  
#打開數據庫鏈接  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法獲取操做遊標  
cur = db.cursor()  
  
#1.查詢操做  
# 編寫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()  #關閉鏈接

 

複製代碼

 

查詢單條數據

複製代碼
# 導入pymysql模塊
import pymysql
# 鏈接database
conn = pymysql.connect(host=「你的數據庫地址」, user=「用戶名」,password=「密碼」,database=「數據庫名」,charset=「utf8」)
# 獲得一個能夠執行SQL語句的光標對象
cursor = conn.cursor()
# 查詢數據的SQL語句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 執行SQL語句
cursor.execute(sql)
# 獲取單條查詢數據
ret = cursor.fetchone()
cursor.close()
conn.close()
# 打印下查詢結果
print(ret)

 
  
複製代碼

 

 

查詢多條數據

複製代碼
# 導入pymysql模塊
import pymysql
# 鏈接database
conn = pymysql.connect(host=「你的數據庫地址」, user=「用戶名」,password=「密碼」,database=「數據庫名」,charset=「utf8」)
# 獲得一個能夠執行SQL語句的光標對象
cursor = conn.cursor()
# 查詢數據的SQL語句
sql = "SELECT id,name,age from USER1;"
# 執行SQL語句
cursor.execute(sql)
# 獲取多條查詢數據
ret = cursor.fetchall()
cursor.close()
conn.close()
# 打印下查詢結果
print(ret)

 

 
  
複製代碼

 

 進階用法

複製代碼
# 能夠獲取指定數量的數據
cursor.fetchmany(3)
# 光標按絕對位置移動1
cursor.scroll(1, mode="absolute")
# 光標按照相對位置(當前位置)移動1
cursor.scroll(1, mode="relative")
複製代碼
相關文章
相關標籤/搜索