大家早上好啊,今天我們繼續(xù)學(xué)習(xí)python操作MySQL(增刪改查)。
大數(shù)據(jù)機(jī)器學(xué)習(xí)數(shù)據(jù)分析爬蟲Python開發(fā)愛好者,?MySQL 是我們經(jīng)常接觸的數(shù)據(jù)庫(kù),它的優(yōu)點(diǎn)好處我就不說(shuō)了,(其實(shí)本人也說(shuō)不出什么,反正是常用的數(shù)據(jù)庫(kù))那么我們?nèi)绾问褂胮ython 對(duì)mysql數(shù)據(jù)庫(kù)進(jìn)行操作呢。下面我來(lái)給大家說(shuō)說(shuō)。
首先連接mysql
在建立連接前我們的python 要安裝pymsql
pip install pymysql
在命令行里輸入 pip install pymysql
下面打開我們的IDE 我使用的是pycharm
# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''
1.0 python連接mysql 并進(jìn)行增刪改查
'''
import pymysql.cursors
'''
連接數(shù)據(jù)庫(kù)
'''
#使用pymysql指令連接數(shù)據(jù)庫(kù)
connection = pymysql.connect(host = '127.0.0.1', #要連接的數(shù)據(jù)庫(kù)的IP地址
user = 'root', #登錄的賬戶名,如果登錄的是最高權(quán)限賬戶則為root
password = '123456', #對(duì)應(yīng)的密碼
db = 'iris', #要連接的數(shù)據(jù)庫(kù)
charset = 'utf8mb4', #設(shè)置編碼格式
#返回到Python的結(jié)果,以什么方式存儲(chǔ),如Dict.Cursor是以字典的方式存儲(chǔ)
#如果不加這行數(shù)據(jù)是以元組方式返回
cursorclass = pymysql.cursors.DictCursor
)
這樣我們就建立了python 同mysql 的連接
創(chuàng)建表
try:
'''
創(chuàng)建表
'''
# 使用cursor()方法獲取操作游標(biāo)
with connection.cursor() as cursor:
# 如果數(shù)據(jù)表已經(jīng)存在使用 execute() 方法刪除表。
cursor.execute("drop table if EXISTS users")
sql = '''create table users (
id int(11) not null auto_increment,
email varchar(255) collate utf8_bin not null,
password varchar(255) collate utf8_bin not null,
primary key (id)
)
engine = InnoDB default charset=utf8 collate=utf8_bin
auto_increment=1;
'''
cursor.execute(sql)
except:
# 發(fā)生錯(cuò)誤時(shí)回滾
connection.rollback()
finally:
# 關(guān)閉連接
connection.close()
插入數(shù)據(jù)
# 從數(shù)據(jù)庫(kù)鏈接中得到cursor的數(shù)據(jù)結(jié)構(gòu)
with connection.cursor() as cursor:
sql = " insert into users(email, password) VALUES (%s, %s)"
cursor.execute(sql,('webmaster@python.org','very_secret'))
# 執(zhí)行到這一行指令時(shí)才是真正改變了數(shù)據(jù)庫(kù),之前只是緩存在內(nèi)存中
connection.commit()
批量插入數(shù)據(jù)
'''
批量插入數(shù)據(jù)
'''
#讀取文件
with open('iris.csv', 'r', encoding='utf-8', newline='') as f:
i = 0 #用來(lái)記錄讀取文件中數(shù)據(jù)的的次數(shù)
z = 0 #用來(lái)記錄讀取文件中數(shù)據(jù)的的次數(shù)
list = []
for line in f:
strs = line.split(',')
data = (strs[0], strs[1], strs[2], strs[3], strs[4].replace("","")) #數(shù)據(jù)的最后一行會(huì)有一個(gè)換行符,用replace替換掉
list.append(data)
i += 1
z += 1
if i >= 10: #用于現(xiàn)在一次插入多少條這里是10條插入一次
with connection.cursor() as cursor:
sql = "insert into iris(sepal_length, sepal_width, petal_length, petal_width, uspecies) "
"VALUES (%s, %s, %s, %s, %s)"
cursor.executemany(sql, list) #批量添加數(shù)據(jù)時(shí) 要用executemany
connection.commit()
print("插入{}條數(shù)據(jù),已插入{}條數(shù)據(jù)".format(i, z))
i = 0 #對(duì)計(jì)數(shù)歸零
list.clear() #清理數(shù)據(jù)列表
if i > 0 : # 循環(huán)文件完畢后,對(duì)剩余的數(shù)據(jù)進(jìn)行插入,(例如小于10的剩余數(shù)據(jù),比如你的文件有55行,剩余的5行就要這樣插入)
cursor.executemany(sql, list)
connection.commit()
查詢數(shù)據(jù)
'''
查詢數(shù)據(jù)
'''
#單一數(shù)據(jù)
with connection.cursor() as cursor:
sql = " select id, email, password from users where email = %s"
cursor.execute(sql,('sfs1100@126.com'))
result = cursor.fetchone() #fetchone()只取出第一條結(jié)果
print(result)
print(type(result))
#多條數(shù)據(jù)
with connection.cursor() as cursor:
sql = " select * from iris where sepal_length > %s"
cursor.execute(sql, (3))
result = cursor.fetchall() #fetchone()取出查詢后的所有數(shù)據(jù)
print(result)
print(type(result))
for each in result:
print(each['uspecies'])
更新數(shù)據(jù)
'''
更新數(shù)據(jù)
'''
with connection.cursor() as cursor:
sql = " update users set email = %s where password = %s"
cursor.execute(sql, ('sfs1100@126.com', 'very_secret'))
connection.commit()
刪除數(shù)據(jù)
'''
刪除數(shù)據(jù)
'''
with connection.cursor() as cursor:
sql = "delete from users where email = %s"
cursor.execute(sql, ('sfs1100@126.com'))
connection.commit()
聯(lián)系客服