Python連接mysql數(shù)據(jù)庫及簡單增刪改查操作示例代碼
1.安裝pymysql
進入cmd,輸入 pip install pymysql:
2.數(shù)據(jù)庫建表
在數(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()方法獲取操作游標(biāo)cur = db.cursor()#查詢操作sql = 'select * from books'try: # 執(zhí)行sql語句 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()
運行結(jié)果:
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()
運行結(jié)果:
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: #錯誤回滾 db.rollback()finally: db.close()
運行結(jié)果:
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語句傳遞參數(shù) cur.execute(sql_delete % (1)) #提交 db.commit()except Exception as e: #錯誤回滾 db.rollback()finally: db.close()
運行結(jié)果:
到此這篇關(guān)于Python連接mysql數(shù)據(jù)庫及簡單增刪改查操作示例代碼的文章就介紹到這了,更多相關(guān)Python連接mysql數(shù)據(jù)庫及增刪改查操作內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python GUI庫圖形界面開發(fā)之PyQt5動態(tài)(可拖動控件大小)布局控件QSplitter詳細使用方法與實例2. ASP動態(tài)include文件3. XML入門的常見問題(三)4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. js開發(fā)中的頁面、屏幕、瀏覽器的位置原理(高度寬度)說明講解(附圖)6. CSS清除浮動方法匯總7. 不要在HTML中濫用div8. XML 非法字符(轉(zhuǎn)義字符)9. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)10. vue跳轉(zhuǎn)頁面常用的幾種方法匯總
