python pymysql庫的常用操作
更新時間:2020年10月16日 08:50:25 作者:Virya
這篇文章主要介紹了python pymysql庫的常用操作,幫助大家更好的利用python操作數(shù)據(jù)庫,感興趣的朋友可以了解下
批量插入
import pymysql def insert_to_mysql(to_db_list): mysql_db = pymysql.connect(host="HOST_IP", port=3306, user="username", password="password", database="db", charset="utf8") cursor = mysql_db.cursor() sql = "INSERT INTO `your_db`.`your_table`(`colum1`, `colum2`, `colum3`) VALUES (%s,%s,%s)" try: # cursor.execute() cursor.executemany(sql, to_db_list) # 批量插入 effect_rows = cursor.rowcount mysql_db.commit() cursor.close() print('數(shù)據(jù)庫添加成功,插入 {}條數(shù)據(jù)'.format(effect_rows)) return effect_rows except Exception as e: mysql_db.rollback() print('數(shù)據(jù)庫執(zhí)行失敗') print(e) return 0 my_list = [] my_list.append(('v1', 'v2', 'v3')) cnt = insert_to_mysql(my_list)
查詢
def get_id_name(): cursor = mysql_db.cursor() sql = "select id, name from `your_db`.`table`" cursor.execute(sql) res = cursor.fetchall() # print(res) return res my_list = get_id_name() for index in range(len(my_list)): print(my_list[index][0]) # id print(my_list[index][1]) # name
更新
def update_by_id(update_list): """根據(jù)ID更新col1, col2, col3 list 依次為 col1, col2, col3, id :param update_list: :return: """ cursor = mysql_db.cursor() sql = "UPDATE `your_db`.`table` SET col1=(%s),col2=(%s),col3=(%s) WHERE id=(%s)" try: # cursor.execute() cursor.executemany(sql, update_list) # 批量插入 mysql_db.commit() cursor.close() print('數(shù)據(jù)庫更新成功') except Exception as e: mysql_db.rollback() print('數(shù)據(jù)庫更新失敗') print(e) my_list = [] my_list.append(('v1', 'v2', 'v3', 'id')) update_by_id(my_list)
以上就是python pymysql庫的常用操作的詳細內(nèi)容,更多關(guān)于python pymysql庫的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- 利用python中pymysql操作MySQL數(shù)據(jù)庫的新手指南
- Python接口自動化淺析pymysql數(shù)據(jù)庫操作流程
- python使用pymysql模塊操作MySQL
- pymysql實現(xiàn)增刪改查的操作指南(python)
- python 基于PYMYSQL使用MYSQL數(shù)據(jù)庫
- Python pymysql模塊安裝并操作過程解析
- python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解
- 在python中使用pymysql往mysql數(shù)據(jù)庫中插入(insert)數(shù)據(jù)實例
- Python使用pymysql模塊操作mysql增刪改查實例分析
- python之pymysql模塊簡單應(yīng)用示例代碼
- wxpython+pymysql實現(xiàn)用戶登陸功能
- 在Python中使用MySQL--PyMySQL的基本使用方法
- Python 中使用 PyMySQL模塊操作數(shù)據(jù)庫的方法
- 使用python連接mysql數(shù)據(jù)庫之pymysql模塊的使用
- Python pymysql操作MySQL詳細
相關(guān)文章
pytorch1.0中torch.nn.Conv2d用法詳解
今天小編就為大家分享一篇pytorch1.0中torch.nn.Conv2d用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01python3使用logging包,如何把日志寫到系統(tǒng)的rsyslog中
這篇文章主要介紹了python3使用logging包,如何把日志寫到系統(tǒng)的rsyslog中的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09跟老齊學(xué)Python之傳說中的函數(shù)編寫條規(guī)
在使用函數(shù)的時候,首先要把它放在對象的層面考量,它不是什么特殊的東西,盡管我們使用了不少篇幅講述它,但它終歸還是一個對象。2014-10-10