zoukankan      html  css  js  c++  java
  • 用python向mysql添加1万条数据最精简的方法

    废话不说,上干

    import pymysql #pip install pymysql
    
    dbinfo = {
        "host": "192.168.1.105",
        "user": "root",
        "password": "你的数据库密码",
        "port": 3306}
    
    class DbConnect:
        def __init__(self, db_cof, database=""):
            # 打开数据库连接
            self.db = pymysql.connect(database=database,
                                      cursorclass=pymysql.cursors.DictCursor,
                                      **db_cof)
    
            # 使用cursor()方法获取操作游标
            self.cursor = self.db.cursor()
    
        def execute(self, sql):
         try:
    
               # 执行SQL语句
               self.cursor.execute(sql)
               # 提交修改
               self.db.commit()
            except Exception as e:
               # 发生错误时回滚
               print(e)
               self.db.rollback()
    
        def close(self):
            # 关闭连接
            self.db.close()
    
    
    if __name__ == '__main__':
        
        insert_sql = "INSERT INTO  数据库名.表名 VALUES"
        add_sql = ''
        for i in range(10000):
            add_sql += "(%s,'test','2020-11-04'), 
    " %str(i)
        sql = insert_sql + add_sql
        finallysql = sql[:-3]
    
        time1 = time.time()
        db = DbConnect(dbinfo, database='数据库名')
        db.execute(finallysql)
        db.close()
        time2 = time.time()
        print("总过耗时:%s" %(time2-time1))

    用python造数据比直接用图形界面快多了。

  • 相关阅读:
    友盟推送
    主流推送平台分析
    “完成”的定义和测试的职责
    HDU 1069 Monkey and Banana
    HDU 5587 Array
    ACM组队安排(hdu校赛)
    逆袭指数(hdu校赛)
    玩骰子(hdu校赛)
    Codeforce 546 A. Soldier and Bananas
    Codeforce 546 B. Soldier and Badges
  • 原文地址:https://www.cnblogs.com/huaniaoyuchong/p/13931536.html
Copyright © 2011-2022 走看看