濮阳杆衣贸易有限公司

主頁 > 知識(shí)庫 > Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫

Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫

熱門標(biāo)簽:電信營(yíng)業(yè)廳400電話申請(qǐng) 幫人做地圖標(biāo)注收費(fèi)算詐騙嗎 遼寧400電話辦理多少錢 溫州旅游地圖標(biāo)注 荊州云電銷機(jī)器人供應(yīng)商 蘇州電銷機(jī)器人十大排行榜 外呼不封號(hào)系統(tǒng) 悟空智電銷機(jī)器人6 江蘇房產(chǎn)電銷機(jī)器人廠家

一、數(shù)據(jù)庫操作

1.1 安裝PyMySQL

pip install PyMySQL

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

python連接test數(shù)據(jù)庫

import pymysql

host = 'localhost'      # 主機(jī)地址
username = 'root'       # 數(shù)據(jù)庫用戶名
password = ''           # 數(shù)據(jù)庫密碼
db_name = 'test'        # 數(shù)據(jù)庫名稱

# 創(chuàng)建connect對(duì)象
connect = pymysql.connect(host=host, user=username, password=password, database=db_name)

# 獲取游標(biāo)對(duì)象
cursor = connect.cursor()

# 查詢數(shù)據(jù)庫版本
cursor.execute('SELECT VERSION()')

# 從查詢結(jié)果集中獲取下一行數(shù)據(jù),返回值為一個(gè)值的序列
result = cursor.fetchone()

# 打印結(jié)果
print(result)

# 關(guān)閉游標(biāo)
cursor.close()

# 關(guān)閉數(shù)據(jù)庫連接
connect.close()

執(zhí)行結(jié)果:
('10.4.17-MariaDB',)

1.3 創(chuàng)建數(shù)據(jù)表

創(chuàng)建一個(gè)默認(rèn)編碼格式為utf8的數(shù)據(jù)表users

id:int類型,不能為空,有自增屬性,主鍵約束

name:varchar類型,長(zhǎng)度最多為10字符,可以為空

age:int類型,可以為空

import pprint
import pymysql

host = 'localhost'      # 主機(jī)地址
username = 'root'       # 數(shù)據(jù)庫用戶名
password = ''           # 數(shù)據(jù)庫密碼
db_name = 'test'        # 數(shù)據(jù)庫名稱

# 創(chuàng)建connect對(duì)象
connect = pymysql.connect(host=host, user=username, password=password, database=db_name)

# 獲取游標(biāo)對(duì)象
cursor = connect.cursor()

# 創(chuàng)建數(shù)據(jù)表的SQL命令
create_sql = '''
CREATE TABLE `users`(
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(10) NULL,
    `age` INT NULL,
    PRIMARY KEY (`id`))
    DEFAULT CHARACTER SET = utf8;
'''
# 創(chuàng)建數(shù)據(jù)表
cursor.execute(create_sql)

# 查詢我們創(chuàng)建的數(shù)據(jù)表的結(jié)構(gòu)
cursor.execute('DESC users')

# 從查詢結(jié)果中獲取結(jié)果的所有(或者剩余)行數(shù)據(jù),返回值為包含序列的序列(例如元組序列)
result = cursor.fetchall()

# 打印結(jié)果
pprint.pprint(result)

# 關(guān)閉游標(biāo)
cursor.close()

# 關(guān)閉數(shù)據(jù)庫連接
connect.close()

執(zhí)行結(jié)果:
(('id', 'int(11)', 'NO', 'PRI', None, 'auto_increment'),
 ('name', 'varchar(10)', 'YES', '', None, ''),
 ('age', 'int(11)', 'YES', '', None, ''))

1.4 插入,查詢數(shù)據(jù)

插入3行數(shù)據(jù):

id:1,name:路飛,age:18
id:2,name:娜美,age:19
id:3,name:索隆,age:20

import pprint
import pymysql

host = 'localhost'      # 主機(jī)地址
username = 'root'       # 數(shù)據(jù)庫用戶名
password = ''           # 數(shù)據(jù)庫密碼
db_name = 'test'        # 數(shù)據(jù)庫名稱

# 創(chuàng)建connect對(duì)象,插入中文時(shí)需要指定編碼格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 獲取游標(biāo)對(duì)象查詢返回字典
cursor = connect.cursor(pymysql.cursors.DictCursor)

# 插入數(shù)據(jù)的SQL命令
insert_sql = '''
INSERT INTO users (id, name, age)
    VALUES (1, '路飛', 18),(2, '娜美', 19),(3, '索隆', 20)
'''

try:
    # 插入數(shù)據(jù)到數(shù)據(jù)表
    cursor.execute(insert_sql)
    # 提交任何掛起的事務(wù)到數(shù)據(jù)庫
    connect.commit()
except Exception as e:
    # 發(fā)送數(shù)據(jù)回滾,回滾到事務(wù)開始時(shí)的狀態(tài)
    connect.rollback()

# 查詢數(shù)據(jù)
cursor.execute('SELECT * FROM users')

# 只返回一行數(shù)據(jù)
# result_one = cursor.fetchone()
# print('---fetchone---')
# pprint.pprint(result_one)

# 返回全部數(shù)據(jù)
result_all = cursor.fetchall()
print('---fetchall---')
pprint.pprint(result_all)

# 關(guān)閉游標(biāo)
cursor.close()

# 關(guān)閉數(shù)據(jù)庫連接
connect.close()

執(zhí)行結(jié)果:
---fetchall---
[{'age': 18, 'id': 1, 'name': '路飛'},
 {'age': 19, 'id': 2, 'name': '娜美'},
 {'age': 20, 'id': 3, 'name': '索隆'}]

1.5 更新,查詢數(shù)據(jù)

更新數(shù)據(jù)id:3,name:山治,age:21

import pprint
import pymysql

host = 'localhost'      # 主機(jī)地址
username = 'root'       # 數(shù)據(jù)庫用戶名
password = ''           # 數(shù)據(jù)庫密碼
db_name = 'test'        # 數(shù)據(jù)庫名稱

# 創(chuàng)建connect對(duì)象,插入中文時(shí)需要指定編碼格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 獲取游標(biāo)對(duì)象查詢返回字典
cursor = connect.cursor(pymysql.cursors.DictCursor)

# 查詢數(shù)據(jù)
cursor.execute('SELECT * FROM users')

# 返回更新前全部數(shù)據(jù)
result_all = cursor.fetchall()
print('---更新前---')
pprint.pprint(result_all)

# 更新數(shù)據(jù)的SQL命令
update_sql = '''
	UPDATE users SET name = '山治',age = 21 WHERE id = 3
'''

try:
    # 更新數(shù)據(jù)到數(shù)據(jù)表
    cursor.execute(update_sql)
    # 提交任何掛起的事務(wù)到數(shù)據(jù)庫
    connect.commit()
except Exception as e:
    # 發(fā)送數(shù)據(jù)回滾,回滾到事務(wù)開始時(shí)的狀態(tài)
    connect.rollback()

# 查詢數(shù)據(jù)
cursor.execute('SELECT * FROM users')

# 返回更新后全部數(shù)據(jù)
result_all = cursor.fetchall()
print('---更新后---')
pprint.pprint(result_all)

# 關(guān)閉游標(biāo)
cursor.close()

# 關(guān)閉數(shù)據(jù)庫連接
connect.close()

執(zhí)行結(jié)果:
---更新前---
[{'age': 18, 'id': 1, 'name': '路飛'},
 {'age': 19, 'id': 2, 'name': '娜美'},
 {'age': 20, 'id': 3, 'name': '索隆'}]
---更新后---
[{'age': 18, 'id': 1, 'name': '路飛'},
 {'age': 19, 'id': 2, 'name': '娜美'},
 {'age': 21, 'id': 3, 'name': '山治'}]

1.6 刪除,查詢數(shù)據(jù)

刪除'age': 19, 'id': 2, 'name': '娜美'該行數(shù)據(jù)

import pprint
import pymysql

host = 'localhost'      # 主機(jī)地址
username = 'root'       # 數(shù)據(jù)庫用戶名
password = ''           # 數(shù)據(jù)庫密碼
db_name = 'test'        # 數(shù)據(jù)庫名稱

# 創(chuàng)建connect對(duì)象,插入中文時(shí)需要指定編碼格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 獲取游標(biāo)對(duì)象查詢返回字典
cursor = connect.cursor(pymysql.cursors.DictCursor)

# 查詢數(shù)據(jù)
cursor.execute('SELECT * FROM users')

# 返回刪除前全部數(shù)據(jù)
result_all = cursor.fetchall()
print('---刪除前---')
pprint.pprint(result_all)

# 刪除數(shù)據(jù)的SQL命令
update_sql = '''
	DELETE FROM users WHERE id = 2
'''

try:
    # 刪除數(shù)據(jù)表的數(shù)據(jù)
    cursor.execute(update_sql)
    # 提交任何掛起的事務(wù)到數(shù)據(jù)庫
    connect.commit()
except Exception as e:
    # 發(fā)送數(shù)據(jù)回滾,回滾到事務(wù)開始時(shí)的狀態(tài)
    connect.rollback()

# 查詢數(shù)據(jù)
cursor.execute('SELECT * FROM users')

# 返回刪除后全部數(shù)據(jù)
result_all = cursor.fetchall()
print('---刪除后---')
pprint.pprint(result_all)

# 關(guān)閉游標(biāo)
cursor.close()

# 關(guān)閉數(shù)據(jù)庫連接
connect.close()

執(zhí)行結(jié)果:
---刪除前---
[{'age': 18, 'id': 1, 'name': '路飛'},
 {'age': 19, 'id': 2, 'name': '娜美'},
 {'age': 21, 'id': 3, 'name': '山治'}]
---刪除后---
[{'age': 18, 'id': 1, 'name': '路飛'}, {'age': 21, 'id': 3, 'name': '山治'}]

二、連接與游標(biāo)對(duì)象的方法

2.1 連接對(duì)象的方法

  • .close()方法:

馬上關(guān)閉數(shù)據(jù)連接(而不是當(dāng)__del__方法被調(diào)用的時(shí)候)。此后連接變得不可用,再次訪問本連接對(duì)象會(huì)觸發(fā)一個(gè)錯(cuò)誤,使用本連接對(duì)象的游標(biāo)對(duì)象,也會(huì)導(dǎo)致例外發(fā)生。在關(guān)閉連接對(duì)象之前,沒有提交(commit)對(duì)數(shù)據(jù)庫的改變將會(huì)導(dǎo)致一個(gè)隱含的回滾動(dòng)作(rollback),這將丟棄之前的數(shù)據(jù)改變操作。

  • .commit()方法:

提交任何掛起的事務(wù)到數(shù)據(jù)庫中。

  • .rollback()方法:

對(duì)于支持事務(wù)的數(shù)據(jù)庫。調(diào)用此方法將導(dǎo)致數(shù)據(jù)庫回滾到事務(wù)開始時(shí)的狀態(tài)。

  • .cursor()方法:

方法返回給定連接上建立的游標(biāo)對(duì)象(Cursor Object),如果數(shù)據(jù)庫沒有提供對(duì)應(yīng)的游標(biāo)對(duì)象,那么有程序來模擬實(shí)現(xiàn)游標(biāo)功能。

2.2 游標(biāo)對(duì)象的方法

  • .close()方法:

立即關(guān)閉游標(biāo)(不論__del__方法是否已被調(diào)用),此后游標(biāo)對(duì)象就變得不可用了。

  • .execute(operation[,parameters])方法:

準(zhǔn)備和執(zhí)行數(shù)據(jù)庫操作。所提供的參數(shù)將會(huì)被綁定到語句中的變量,變量的定義和數(shù)據(jù)庫模塊有關(guān)。

  • .executemany(operation,seq_of_parameters)方法:

準(zhǔn)備和執(zhí)行數(shù)據(jù)庫操作,然后以序列形式的函數(shù)來執(zhí)行該操作。

  • .fetchone()方法:

從查詢結(jié)果中獲取下一行數(shù)據(jù),返回值為一個(gè)值的序列,如果沒有更多數(shù)據(jù)則返回None。

  • .fetchmany([size=cursor.arraysize])方法:

從查詢結(jié)果中獲取下一組行數(shù)據(jù),返回值為包含序列的序列,如果沒有數(shù)據(jù)返回時(shí),則返回空序列。每次調(diào)用要獲取的行數(shù)由參數(shù)指定,如果沒有指定行數(shù),則游標(biāo)的arraysize屬性決定要獲取的行數(shù)。

  • .fetchall()方法:

從查詢結(jié)果中獲取所有(或者剩余)行數(shù)據(jù),返回值為包含序列的序列。

  • .nextset()方法:

此方法將游標(biāo)跳到下一個(gè)可用的結(jié)果集并丟棄當(dāng)前結(jié)果集的所有行,如果沒有更有查詢結(jié)果集則返回None,否則返回True,接下來的fetch操作將會(huì)從新結(jié)果集返回?cái)?shù)據(jù)了。

  • .setinputsizes(sizes)方法:

此方法可用在調(diào)用.execute系列方法之前使用,用于預(yù)定義內(nèi)存區(qū)域。size參數(shù)接收一個(gè)序列類型的值,每一個(gè)元素對(duì)應(yīng)一個(gè)輸入?yún)?shù),該元素應(yīng)該是一個(gè)類型對(duì)象,對(duì)于將要使用的參數(shù),或者是一個(gè)整數(shù),用于指定字符串的最大長(zhǎng)度。如果元素是None,則沒有預(yù)定義的內(nèi)存區(qū)域作為保留區(qū)域。

  • .setoutputsize(size[,column])方法:

為一個(gè)很大的列設(shè)置緩沖區(qū)大小,不指定將使用默認(rèn)大小。

三、事務(wù)

事務(wù)是數(shù)據(jù)庫管理系統(tǒng)執(zhí)行過程中的一個(gè)邏輯單位,由一個(gè)有限的數(shù)據(jù)庫操作序列構(gòu)成,事務(wù)的目的性是為了保證數(shù)據(jù)的一致性。假設(shè)銀行轉(zhuǎn)賬操作,從A賬戶轉(zhuǎn)賬100元到B賬戶需要進(jìn)行至少兩次的數(shù)據(jù)庫修改操作,A賬戶余額需要減少100元,B賬戶余額需要增加100元,如果因?yàn)橛捎谕獠吭驅(qū)е鲁绦蛞馔饨K止,就會(huì)操作數(shù)據(jù)出錯(cuò),事務(wù)就是防止此情況的發(fā)生。

數(shù)據(jù)庫事務(wù)擁有四個(gè)特性,習(xí)慣稱之為ACID特性:

1、原子性(Atomicity):事務(wù)作為一個(gè)整體被執(zhí)行,包含在其中的對(duì)數(shù)據(jù)庫的操作要么全部被執(zhí)行,要么不執(zhí)行。
2、一致性(Consistency):事務(wù)應(yīng)確保數(shù)據(jù)庫的狀態(tài)從一個(gè)一致狀態(tài)轉(zhuǎn)變?yōu)榱硪粋€(gè)一致狀態(tài),一致狀態(tài)的含義是數(shù)據(jù)庫中的數(shù)據(jù)應(yīng)滿足完整性約束。
3、隔離性(Isolation):多個(gè)事務(wù)并發(fā)執(zhí)行時(shí),一個(gè)事務(wù)的執(zhí)行不應(yīng)影響其他事務(wù)的執(zhí)行。
4、持久性(Durability):已被提交的事務(wù)對(duì)數(shù)據(jù)庫的修改應(yīng)該永久保存在數(shù)據(jù)庫中。

import pprint
import pymysql

host = 'localhost'      # 主機(jī)地址
username = 'root'       # 數(shù)據(jù)庫用戶名
password = ''           # 數(shù)據(jù)庫密碼
db_name = 'test'        # 數(shù)據(jù)庫名稱

# 創(chuàng)建connect對(duì)象,插入中文時(shí)需要指定編碼格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 獲取游標(biāo)對(duì)象查詢返回字典
cursor = connect.cursor(pymysql.cursors.DictCursor)

# 正確的插入數(shù)據(jù)的SQL命令
insert_sql1 = '''
INSERT INTO users (name, age)
    VALUES ('羅賓', 18),('喬巴', 16)
'''

# 錯(cuò)誤的插入數(shù)據(jù)的SQL命令
insert_sql2 = '''
INSERT INTO users (name, age)
    VALUES ('弗蘭奇')
'''

try:
    # 插入數(shù)據(jù)到數(shù)據(jù)表
    cursor.execute(insert_sql1)
    cursor.execute(insert_sql2)
    # 提交任何掛起的事務(wù)到數(shù)據(jù)庫
    connect.commit()
except Exception as e:
    # 執(zhí)行失敗發(fā)送數(shù)據(jù)回滾,回滾到事務(wù)開始時(shí)的狀態(tài)
    connect.rollback()

# 查詢數(shù)據(jù)
cursor.execute('SELECT * FROM users')

# 返回全部數(shù)據(jù)
result_all = cursor.fetchall()
print('---fetchall---')
pprint.pprint(result_all)

# 關(guān)閉游標(biāo)
cursor.close()

# 關(guān)閉數(shù)據(jù)庫連接
connect.close()

上例中執(zhí)行了兩條SQL語句,一條正確的一條錯(cuò)誤的,只要有一個(gè)錯(cuò)誤,兩條都不會(huì)生效,rollback方法會(huì)回滾當(dāng)前游標(biāo)的所有操作。

到此這篇關(guān)于Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Python操作MySQL內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • MYSQL數(shù)據(jù)庫基礎(chǔ)之Join操作原理
  • MySQL系列之開篇 MySQL關(guān)系型數(shù)據(jù)庫基礎(chǔ)概念
  • Mysql數(shù)據(jù)庫索引面試題(程序員基礎(chǔ)技能)
  • MySql數(shù)據(jù)庫基礎(chǔ)知識(shí)點(diǎn)總結(jié)
  • 一篇文章帶你了解MySQL數(shù)據(jù)庫基礎(chǔ)

標(biāo)簽:景德鎮(zhèn) 黃山 濟(jì)南 三沙 宿遷 欽州 喀什 臺(tái)灣

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫》,本文關(guān)鍵詞  Python,基礎(chǔ),之,操作,MySQL,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫》相關(guān)的同類信息!
  • 本頁收集關(guān)于Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    漯河市| 西畴县| 略阳县| 遂平县| 咸阳市| 元谋县| 东明县| 休宁县| 赤壁市| 东乌珠穆沁旗| 绩溪县| 河西区| 开封县| 湖州市| 朝阳区| 鹿邑县| 新和县| 宣恩县| 临泉县| 藁城市| 长垣县| 寿光市| 尖扎县| 微博| 青铜峡市| 双柏县| 安乡县| 富裕县| 朝阳县| 固原市| 榆林市| 常山县| 辛集市| 汉川市| 建平县| 合江县| 竹溪县| 怀化市| 阿拉善右旗| 成安县| 安达市|