python pymysql庫(kù)的常用操作
批量插入
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ù)庫(kù)添加成功,插入 {}條數(shù)據(jù)’.format(effect_rows)) return effect_rows except Exception as e: mysql_db.rollback() print(’數(shù)據(jù)庫(kù)執(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ù)庫(kù)更新成功’) except Exception as e: mysql_db.rollback() print(’數(shù)據(jù)庫(kù)更新失敗’) print(e) my_list = []my_list.append((’v1’, ’v2’, ’v3’, ’id’))update_by_id(my_list)
以上就是python pymysql庫(kù)的常用操作的詳細(xì)內(nèi)容,更多關(guān)于python pymysql庫(kù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解CSS不受控制的position fixed2. ie6,ie7,ie8完美支持position:fixed的終極解決方案3. XML中顯示HTML的小技巧4. 詳解如何使用Net將HTML簡(jiǎn)歷導(dǎo)出為PDF格式5. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂(lè)代碼6. Properties 持久的屬性集的實(shí)例詳解7. html清除浮動(dòng)的6種方法示例8. asp+JMAIL實(shí)現(xiàn)發(fā)送郵件9. jsp文件下載功能實(shí)現(xiàn)代碼10. CSS linear-gradient屬性案例詳解
