首页 / PYTHON / python对数据库操作
python对数据库操作
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python对数据库操作,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2032字,纯文字阅读大概需要3分钟。
内容图文
![python对数据库操作](/upload/InfoBanner/zyjiaocheng/873/6527fdf7f05b4146a43c5df68485f8ac.jpg)
# -*- coding: utf-8 -*- """ @description: xxx @time: 2019/12/22 1:03 @author: baojinlong """ import random import time import datetime import pymysql from faker import Faker import pandas as pd # 从全路径下导入工具类 class MySqlUtils(object): # init def __init__(self, host, user, password, db_name, port=3306, charset='utf8'): self.conn = pymysql.Connect( host=host, port=port, user=user, passwd=password, db=db_name, charset=charset ) self.cursor = self.conn.cursor() # insert def insert(self, tbName, field, values): insSql = 'insert into %s(%s) values (%s)' % (tbName, field, values) print('sql=', insSql) return self.excute(insSql) # select def select(self, tbName, field='*', where='1=1'): selSql = "select %s from %s where %s" % (field, tbName, where) print('sql=', selSql) return self.excute(selSql) # update def update(self, keyValues, tbName, where='1=1'): setValue = '' for k, v in keyValues.items(): setValue += '`%s`="%s",' % (k, v) if where: where = " where " + where updateSql = "update %s set %s %s" % (tbName, setValue[:-1], where) return self.excute(updateSql) # delete def delete(self, tbName, where='1=1'): delSql = "delete from %s %s where " % (tbName, where) return self.excute(delSql) # execute def excute(self, sql): try: if sql.find('select') != -1: self.cursor.execute(sql) return self.cursor.fetchall() elif sql.find('insert') != -1 or sql.find('update') != -1 or sql.find('delete') != -1: self.cursor.execute(sql) self.conn.commit() return True else: return False except Exception as e: print(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + '--' + str(e)) return False # __del__ def __del__(self): self.cursor.close() self.conn.close() if __name__ == '__main__': # 创建类 host='xxxxxxxxxxxxx' user='xxxxx' port=xxxxx passwd='xxxxxxx' db_name='xxxxxx' table_name = 'xxxxx' mySqlUtils = MySqlUtils(host, user, passwd, db_name) # 读取文件 all_data = [data for data in open('D:\Data_script\wx_union_id.txt', 'r')] print("读取到文件大小", len(all_data)) for index, value in enumerate(all_data): keyValues = {'wx_union_id': value} mySqlUtils.update(keyValues, table_name, f'id={index + 1}') else: print('数据全部更新完毕')
内容总结
以上是互联网集市为您收集整理的python对数据库操作全部内容,希望文章能够帮你解决python对数据库操作所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。