python3.6使用pymysql連接Mysql數(shù)據(jù)庫
python3.6使用pymysql連接Mysql數(shù)據(jù)庫及簡單的增刪改查操作,供大家參考,具體內(nèi)容如下
折騰好半天的數(shù)據(jù)庫連接,由于之前未安裝pip ,而且自己用的Python 版本為3.6. 只能用 pymysql 來連接數(shù)據(jù)庫,(如果有和我一樣未安裝 pip 的朋友請 點這里windows下python安裝pip簡易教程),下邊簡單介紹一下連接的過程,以及簡單的增刪改查操作。
1.通過pip 安裝pymysql
進入 cmd 輸入 pip install pymysql
回車等待安裝完成;
安裝完成后出現(xiàn)如圖相關(guān)信息,表示安裝成功。
2.測試連接
import pymysql #導(dǎo)入 pymysql ,如果編譯未出錯,即表示 pymysql 安裝成功
簡單的增刪改查操作
示例表結(jié)構(gòu)
2.1查詢操作
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 對應(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 e finally: db.close() #關(guān)閉連接
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: #錯誤回滾 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: #錯誤回滾 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: #錯誤回滾 db.rollback() finally: db.close()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python數(shù)據(jù)處理67個pandas函數(shù)總結(jié)看完就用
這篇文章主要介紹了python數(shù)據(jù)處理67個pandas函數(shù)的梳理總結(jié),看完就可以去用了,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11修改 CentOS 6.x 上默認(rèn)Python的方法
這篇文章主要介紹了修改 CentOS 6.x 上默認(rèn)Python的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09在Python操作時間和日期之a(chǎn)sctime()方法的使用
這篇文章主要介紹了在Python操作時間和日期之a(chǎn)sctime()方法的使用,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05python 寫函數(shù)在一定條件下需要調(diào)用自身時的寫法說明
這篇文章主要介紹了python 寫函數(shù)在一定條件下需要調(diào)用自身時的寫法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06selenium2.0中常用的python函數(shù)匯總
這篇文章主要介紹了selenium2.0中常用的python函數(shù),總結(jié)分析了selenium2.0中常用的python函數(shù)的功能、原理與基本用法,需要的朋友可以參考下2019-08-08