国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python3.6連接mysql數(shù)據(jù)庫及增刪改查操作詳解

2020-02-15 21:17:27
字體:
供稿:網(wǎng)友

折騰好半天的數(shù)據(jù)庫連接,由于之前未安裝 pip ,而且自己用的python 版本為3.6. 只能用 pymysql 來連接數(shù)據(jù)庫,下邊 簡單介紹一下 連接的過程,以及簡單的增刪改查操作。

1.通過 pip 安裝 pymysql

進(jìn)入 cmd  輸入  pip install pymysql  

回車等待安裝完成;

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

2.測試連接

import pymysql #導(dǎo)入 pymysql

如果編譯未出錯(cuò),即表示 pymysql 安裝成功

簡單的增刪改查操作

示例表結(jié)構(gòu)

2.1查詢操作i

import pymysql #導(dǎo)入 pymysql #打開數(shù)據(jù)庫連接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 efinally:

2.2插入操作

import pymysql#2.插入操作db= pymysql.connect(host="localhost",user="root", 	password="123456",db="test",port=3307) # 使用cursor()方法獲取操作游標(biāo)cur = db.cursor() sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')""" try:	cur.execute(sql_insert)	#提交	db.commit()except Exception as e:	#錯(cuò)誤回滾	db.rollback() finally:	db.close()

2.3更新操作

import pymysql#3.更新操作db= pymysql.connect(host="localhost",user="root", 	password="123456",db="test",port=3307) # 使用cursor()方法獲取操作游標(biāo)cur = db.cursor() sql_update ="update user set username = '%s' where id = %d" try:	cur.execute(sql_update % ("xiongda",3)) #像sql語句傳遞參數(shù)	#提交	db.commit()except Exception as e:	#錯(cuò)誤回滾	db.rollback() finally:	db.close()

2.4刪除操作

import pymysql#4.刪除操作db= pymysql.connect(host="localhost",user="root", 	password="123456",db="test",port=3307) # 使用cursor()方法獲取操作游標(biāo)cur = db.cursor() sql_delete ="delete from user where id = %d" try:	cur.execute(sql_delete % (3)) #像sql語句傳遞參數(shù)	#提交	db.commit()except Exception as e:	#錯(cuò)誤回滾	db.rollback() finally:	db.close()

更多關(guān)于python3.6 連接mysql數(shù)據(jù)庫及增刪改查操作的相關(guān)文章大家可以點(diǎn)擊下面的相關(guān)鏈接

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 长治县| 青海省| 通海县| 中卫市| 宁蒗| 新野县| 康平县| 二连浩特市| 锡林郭勒盟| 三都| 墨江| 刚察县| 安顺市| 涞水县| 新民市| 白水县| 湖北省| 乐陵市| 台湾省| 开化县| 温州市| 华宁县| 阿拉尔市| 清镇市| 灵丘县| 淮北市| 镇坪县| 阳春市| 布尔津县| 三明市| 定南县| 万盛区| 通山县| 夏津县| 静乐县| 松桃| 客服| 兴义市| 永福县| 阿合奇县| 东丽区|