av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

瀏覽:139日期:2022-07-15 11:19:45

1.安裝pymysql

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

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

2.數(shù)據(jù)庫(kù)建表

在數(shù)據(jù)庫(kù)中,建立一個(gè)簡(jiǎn)單的表,如圖:

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

3.簡(jiǎn)單操作

3.1查詢操作

#coding=utf-8#連接數(shù)據(jù)庫(kù)測(cè)試import pymysql#打開數(shù)據(jù)庫(kù)db = pymysql.connect(host='localhost',user='root',password='root',db='test')#使用cursor()方法獲取操作游標(biāo)cur = db.cursor()#查詢操作sql = 'select * from books'try: # 執(zhí)行sql語(yǔ)句 cur.execute(sql) results = cur.fetchall() #遍歷結(jié)果 for rows in results: id = rows[0] name = rows[1] price = rows[2] bookcount = rows[3] author = rows[4] print('id: {}, name: {}, price: {}, bookcount: {}, author: {}'.format(id,name,price,bookcount,author))except Exception as e: raise efinally: db.close()

運(yùn)行結(jié)果:

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

3.2插入操作

#coding=utf-8#插入操作import pymysqldb = pymysql.connect(host='localhost',user='root',password='root',db='test')cur = db.cursor()sql = '''insert into books(id,bookname,price,bookCount,author) values (4,’三體’,20,3,’劉慈欣’)'''try: cur.execute(sql) #提交 db.commit()except Exception as e: #錯(cuò)誤回滾 db.rollback()finally: db.close()

運(yùn)行結(jié)果:

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

3.3更新操作

#coding=utf-8#更新操作import pymysqldb = pymysql.connect(host='localhost',user='root',password='root',db='test')# 使用cursor()方法獲取游標(biāo)cur = db.cursor()sql_update = 'update books set bookname = ’%s’,author = ’%s’ where id = %d'try: cur.execute(sql_update % ('邊城','沈從文',4)) #提交 db.commit()except Exception as e: #錯(cuò)誤回滾 db.rollback()finally: db.close()

運(yùn)行結(jié)果:

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

3.4刪除操作

#coding=utf-8#刪除操作import pymysqldb = pymysql.connect(host='localhost',user='root',password='root',db='test')#使用cursor()獲取操作游標(biāo)cur = db.cursor()sql_delete = 'delete from books where id = %d'try: #向sql語(yǔ)句傳遞參數(shù) cur.execute(sql_delete % (1)) #提交 db.commit()except Exception as e: #錯(cuò)誤回滾 db.rollback()finally: db.close()

運(yùn)行結(jié)果:

Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼

到此這篇關(guān)于Python連接mysql數(shù)據(jù)庫(kù)及簡(jiǎn)單增刪改查操作示例代碼的文章就介紹到這了,更多相關(guān)Python連接mysql數(shù)據(jù)庫(kù)及增刪改查操作內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: www亚洲精品 | 天堂网色 | 91精品中文字幕一区二区三区 | av中文在线播放 | 欧美性受xxxx | 凹凸日日摸日日碰夜夜 | 免费观看一级毛片 | 免费 视频 1级 | 欧美日韩大陆 | 欧美黑人狂野猛交老妇 | 成人免费在线观看 | 成人免费精品 | 国产成人精品午夜视频免费 | 日韩毛片免费看 | 乱一性一乱一交一视频a∨ 色爱av | 亚洲aⅴ | 欧洲性生活视频 | 午夜99 | 婷婷综合五月天 | 亚洲欧洲av在线 | 羞羞视频免费观看入口 | 中文字幕一区二区三区在线视频 | www亚洲精品 | 精品久久久久久久久久久 | 日韩色图在线观看 | 久草.com | 亚洲精品一区二区三区蜜桃久 | 精品综合久久久 | 午夜www| 欧美日一区二区 | 欧美精品网 | 欧美日韩综合一区 | www久久国产| 久久成人av电影 | 久久美国| 国产精品视频一二三区 | 日韩视频 中文字幕 | 精品国产欧美 | 蜜桃免费一区二区三区 | 日韩高清在线 | 成人精品一区二区三区中文字幕 |