日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 综合教程 >内容正文

综合教程

Python连接MySQL数据库之pymysql模块使用

發(fā)布時(shí)間:2024/8/26 综合教程 39 生活家
生活随笔 收集整理的這篇文章主要介紹了 Python连接MySQL数据库之pymysql模块使用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python3連接MySQL

本文介紹Python3連接MySQL的第三方庫(kù)--PyMySQL的基本使用。

PyMySQL介紹

PyMySQL 是在 Python3.x 版本中用于連接 MySQL 服務(wù)器的一個(gè)庫(kù),Python2中則使用mysqldb。

Django中也可以使用PyMySQL連接MySQL數(shù)據(jù)庫(kù)。

PyMySQL安裝

#終端中安裝pymysql
pip install pymysql
python3.6 使用 pymysql 連接 Mysql 數(shù)據(jù)庫(kù)及 簡(jiǎn)單的增刪改查操作

折騰好半天的數(shù)據(jù)庫(kù)連接,由于之前未安裝 pip ,而且自己用的python 版本為3.6. 只能用 pymysql 來連接數(shù)據(jù)庫(kù),(如果有和我一樣未安裝 pip 的朋友請(qǐng) 點(diǎn)這里http://blog.csdn.net/qq_37176126/article/details/72824404 ),下邊 簡(jiǎn)單介紹一下 連接的過程,以及簡(jiǎn)單的增刪改查操作。
1.通過 pip 安裝 pymysql

進(jìn)入 cmd 輸入 pip install pymysql
回車等待安裝完成;

安裝完成后出現(xiàn)如圖相關(guān)信息,表示安裝成功。

連接數(shù)據(jù)庫(kù)

MySQL 連接


使用mysql二進(jìn)制方式連接

您可以使用MySQL二進(jìn)制方式進(jìn)入到mysql命令提示符下來連接MySQL數(shù)據(jù)庫(kù)。

實(shí)例

以下是從命令行中連接mysql服務(wù)器的簡(jiǎn)單實(shí)例:

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

在登錄成功后會(huì)出現(xiàn) mysql> 命令提示窗口,你可以在上面執(zhí)行任何 SQL 語句。

以上命令執(zhí)行后,登錄成功輸出結(jié)果如下:

#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.

在以上實(shí)例中,我們使用了root用戶登錄到mysql服務(wù)器,當(dāng)然你也可以使用其他mysql用戶登錄。

如果用戶權(quán)限足夠,任何用戶都可以在mysql的命令提示窗口中進(jìn)行SQL操作。

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

mysql> exit
Bye

創(chuàng)建數(shù)據(jù)庫(kù)

#-- 創(chuàng)建一個(gè)名為day59的數(shù)據(jù)庫(kù)


cerate database day59;
# -- 使用day59數(shù)據(jù)庫(kù)
 use day59;
#-- 創(chuàng)建一個(gè)userinfo表
 create table userinfo (id int auto_increment primary key,name varchar(10) not null, pwd varchar(18) not null );

#-- 查看表結(jié)構(gòu)是否正確
desc userinfo;

#-- 添加3條測(cè)試數(shù)據(jù) insert into userinfo (name, pwd) values ("alex", "alex3714"),("xiaohei", "123456"),("yimi", "654321"); #-- 查看數(shù)據(jù) select * from userinfo; #-- 根據(jù)特定的用戶名和密碼從數(shù)據(jù)庫(kù)中檢索 select * from userinfo where name="alex" and pwd="alex3714";



注意事項(xiàng)

在進(jìn)行本文以下內(nèi)容之前需要注意:

你有一個(gè)MySQL數(shù)據(jù)庫(kù),并且已經(jīng)啟動(dòng)。
你有可以連接該數(shù)據(jù)庫(kù)的用戶名和密碼
你有一個(gè)有權(quán)限操作的database

基本使用

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
# 定義要執(zhí)行的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;
"""
# 執(zhí)行SQL語句
cursor.execute(sql)
# 關(guān)閉光標(biāo)對(duì)象
cursor.close()
# 關(guān)閉數(shù)據(jù)庫(kù)連接
conn.close()

#注意:harset="utf8",中間沒有空格,因?yàn)閙ySql不支持

返回字典格式數(shù)據(jù):

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句并且將結(jié)果作為字典返回的游標(biāo)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定義要執(zhí)行的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;
"""
# 執(zhí)行SQL語句
cursor.execute(sql)
# 關(guān)閉光標(biāo)對(duì)象
cursor.close()
# 關(guān)閉數(shù)據(jù)庫(kù)連接
conn.close()

注意:

charset=“utf8”,編碼不要寫成"utf-8"

數(shù)據(jù)庫(kù)版登錄


增刪改查操作

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
# 執(zhí)行SQL語句
cursor.execute(sql, [username, age])
# 提交事務(wù)
conn.commit()
cursor.close()
conn.close()


mysql端:

插入數(shù)據(jù)失敗回滾

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 執(zhí)行SQL語句
    cursor.execute(sql, [username, age])
    # 提交事務(wù)
    conn.commit()
except Exception as e:
    # 有異常,回滾事務(wù)
    conn.rollback()
cursor.close()
conn.close()



獲取插入數(shù)據(jù)的ID(關(guān)聯(lián)操作時(shí)會(huì)用到)

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 執(zhí)行SQL語句
    cursor.execute(sql, [username, age])
    # 提交事務(wù)
    conn.commit()
    # 提交之后,獲取剛插入的數(shù)據(jù)的ID
    last_id = cursor.lastrowid
except Exception as e:
    # 有異常,回滾事務(wù)
    conn.rollback()
cursor.close()
conn.close()

批量執(zhí)行

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

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



由于數(shù)據(jù)庫(kù)的編碼格式不一樣所以出現(xiàn)亂碼:

創(chuàng)建數(shù)據(jù)庫(kù)的時(shí)候指定編碼需要:

創(chuàng)建列表的時(shí)候也要指定一下,避免亂碼:

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
sql = "DELETE FROM USER1 WHERE id=%s;"
try:
    cursor.execute(sql, [4])
    # 提交事務(wù)
    conn.commit()
except Exception as e:
    # 有異常,回滾事務(wù)
    conn.rollback()
cursor.close()
conn.close()


# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
# 修改數(shù)據(jù)的SQL語句
sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
username = "Alex"
age = 80
try:
    # 執(zhí)行SQL語句
    cursor.execute(sql, [age, username])
    # 提交事務(wù)
    conn.commit()
except Exception as e:
    # 有異常,回滾事務(wù)
    conn.rollback()
cursor.close()
conn.close()


#查詢操作

import pymysql  #導(dǎo)入 pymysql  
  
#打開數(shù)據(jù)庫(kù)連接  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法獲取操作游標(biāo)  
cur = db.cursor()  
  
#1.查詢操作  
# 編寫sql 查詢語句  user 對(duì)應(yīng)我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #執(zhí)行sql語句  
  
    results = cur.fetchall()    #獲取查詢的所有記錄  
    print("id","name","password")  
    #遍歷結(jié)果  
    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()  #關(guān)閉連接  

查詢單條數(shù)據(jù)

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
# 查詢數(shù)據(jù)的SQL語句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 執(zhí)行SQL語句
cursor.execute(sql)
# 獲取單條查詢數(shù)據(jù)
ret = cursor.fetchone()
cursor.close()
conn.close()
# 打印下查詢結(jié)果
print(ret)


查詢多條數(shù)據(jù)

# 導(dǎo)入pymysql模塊
import pymysql
# 連接database
conn = pymysql.connect(host=“你的數(shù)據(jù)庫(kù)地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫(kù)名”,charset=“utf8”)
# 得到一個(gè)可以執(zhí)行SQL語句的光標(biāo)對(duì)象
cursor = conn.cursor()
# 查詢數(shù)據(jù)的SQL語句
sql = "SELECT id,name,age from USER1;"
# 執(zhí)行SQL語句
cursor.execute(sql)
# 獲取多條查詢數(shù)據(jù)
ret = cursor.fetchall()
cursor.close()
conn.close()
# 打印下查詢結(jié)果
print(ret)


進(jìn)階用法

# 可以獲取指定數(shù)量的數(shù)據(jù)
cursor.fetchmany(3)
# 光標(biāo)按絕對(duì)位置移動(dòng)1
cursor.scroll(1, mode="absolute")
# 光標(biāo)按照相對(duì)位置(當(dāng)前位置)移動(dòng)1
cursor.scroll(1, mode="relative")

總結(jié)

以上是生活随笔為你收集整理的Python连接MySQL数据库之pymysql模块使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。