国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

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

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

1.安裝pymysql

進入cmd,輸入 pip install pymysql:

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

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

在數(shù)據(jù)庫中,建立一個簡單的表,如圖:

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

3.簡單操作

3.1查詢操作

#coding=utf-8#連接數(shù)據(jù)庫測試import pymysql#打開數(shù)據(jù)庫db = pymysql.connect(host='localhost',user='root',password='root',db='test')#使用cursor()方法獲取操作游標cur = db.cursor()#查詢操作sql = 'select * from books'try: # 執(zhí)行sql語句 cur.execute(sql) results = cur.fetchall() #遍歷結果 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()

運行結果:

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

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: #錯誤回滾 db.rollback()finally: db.close()

運行結果:

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

3.3更新操作

#coding=utf-8#更新操作import pymysqldb = pymysql.connect(host='localhost',user='root',password='root',db='test')# 使用cursor()方法獲取游標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: #錯誤回滾 db.rollback()finally: db.close()

運行結果:

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

3.4刪除操作

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

運行結果:

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

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

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 松潘县| 隆子县| 富平县| 四子王旗| 灌云县| 北宁市| 日喀则市| 平潭县| 蕉岭县| 罗源县| 盐源县| 乐都县| 重庆市| 通城县| 建湖县| 张掖市| 青海省| 沐川县| 洮南市| 晋州市| 怀宁县| 神池县| 台中县| 新巴尔虎右旗| 张家川| 时尚| 祁阳县| 龙州县| 浮山县| 江川县| 新乡市| 泸水县| 聂拉木县| 项城市| 启东市| 安龙县| 甘肃省| 泽库县| 云龙县| 永靖县| 天峻县|