使用Python脚本写入MongoDB数据

使用Python脚本对MongoDB数据库内插入数据

1、使用python创建项目MongoDB(名字随意),如下图:

2、在项目下创建DB.conf文件,把可配置的项写入到文件内,如下图:

数据库IP、数据库端口、数据库名字、集合名字(相当于MySQL的表名)、插入的数据、插入数据的条数及脚本共运行时间

 3、创建mongoDB.py文件,如下图:

首先需要一个配置文件操作的类class Config()类,类下面有一个用来获取配置文件的绝对路径的方法def get_config_path(),并且有一个获取配置文件内参数值的def read_config()

 其次需要一个操作MongoDB的类class MongoDB(),类下面有个初始化方法def __init__(),还有个用来连接数据库的方法def connecting(),还有一个以插入总条数来运行的方法def start_insert_num()与 以配置运行时间来运行的方法def start_insert_time()

  1 # @File    : mongoDB_Insert.py
  2 # @Time    : 2018/12/13 10:28
  3 import os,time,configparser
  4 from pymongo import MongoClient
  5 
  6 class MongoDB():
  7 
  8     def __init__(self):
  9         '''
 10         初始化操作
 11         :param host:MongoDB Ip
 12         :param port: MongoDB Port
 13         :param db_name: MongoDB Name
 14         :param collection: MongoDB  Collection Name
 15         '''  
 16         self.conf_path = Config().get_config_path()
 17         self.host = Config().read_config(self.conf_path,"MONGODB_CONF","host")
 18         self.port = int(Config().read_config(self.conf_path,"MONGODB_CONF","port"))
 19         self.db_name = Config().read_config(self.conf_path,"MONGODB_CONF","db_name")
 20         self.collection = Config().read_config(self.conf_path,"MONGODB_CONF","collection_name")
 21         self.insert_data = Config().read_config(self.conf_path,"INSERT_DATA","insert_data")
 22         self.insert_num =int((Config().read_config(self.conf_path,"INSERT_NUM","insert_num")))
 23         self.insert_time =int((Config().read_config(self.conf_path,"INSERT_TIME","insert_time")))
 24 
 25     def connecting(self):
 26         '''
 27         DB连接
 28         :return:    my_collection
 29         '''
 30         try:
 31             conn = MongoClient(host=self.host,port=self.port)
 32             my_db = conn[self.db_name]
 33             my_collection = my_db[self.collection]
 34             return my_collection
 35         except Exception as e:
 36             print('连接失败!错误原因:{}'.format(e))
 37             raise e
 38 
 39     def start_insert_num(self):
 40         '''
 41         插入数据,配置共插入多少数据
 42         :return:None
 43         '''
 44         my_set = self.connecting()
 45         try:
 46             i = 0
 47             start_time = int(time.time() * 1000)
 48             while True:
 49                 my_set.insert((eval((self.insert_data))))
 50                 i += 1
 51                 print('插入{}条数据。'.format(i))
 52                 if i == self.insert_num:
 53                     break
 54             end_time = int(time.time() * 1000)
 55             print('插入数据成功。共插入{}条数据,耗时{}ms。'.format(self.insert_num,end_time - start_time))
 56             input('按回车键结束程序......')
 57         except Exception as e:
 58             print('插入数据失败!失败原因:{}'.format(e))
 59             raise e
 60 
 61     def start_insert_time(self):
 62         '''
 63         插入数据,配置共运行时间
 64         :return:None
 65         '''
 66         my_set = self.connecting()
 67         try:
 68             i = 0
 69             start_time = int(time.time() * 1000)
 70             while True:
 71                 my_set.insert((eval((self.insert_data))))
 72                 i += 1
 73                 print('插入{}条数据。'.format(i))
 74                 if int(time.time()*1000) >= (start_time+self.insert_time):
 75                     break
 76             print('插入数据成功。共插入{}条数据,耗时{}ms。'.format(i,self.insert_time))
 77             input('按回车键结束程序......')
 78         except Exception as e:
 79             print('插入数据失败!失败原因:{}'.format(e))
 80             raise e
 81 
 82 class Config():
 83     '''
 84     读取配置文件类
 85     '''
 86 
 87     def get_config_path(self):
 88         '''
 89         获取配置文件的绝对路径
 90         :return: 配置文件的绝对路径
 91         '''
 92         try:
 93             conf_path = os.path.split(os.path.realpath(__file__))[0] + r"\DB.conf"
 94             return conf_path
 95         except Exception as e:
 96             print('出错啦!!!错误原因:{}'.format(e))
 97             raise e
 98 
 99     def read_config(self,conf_path,section,option):
100         '''
101         读取配置文件
102         :param conf_path:配置文件绝对路径
103         :param section:
104         :param option:
105         :return: 配置文件内的value
106         '''
107         try:
108             cf = configparser.ConfigParser()
109             cf.read(conf_path)
110             value = cf.get(section=section, option=option)
111             return value
112         except Exception as e:
113             print('读取配置文件失败!失败原因:{}'.format(e))
114             raise e
115 
116 if __name__ == '__main__':
117     #两种不同的运行方式
118     #MongoDB().start_insert_num()
119     MongoDB().start_insert_time()

 每个人的代码写法不一样,有的喜欢写到一个类里面,有的喜欢分为多个模块写,有的喜欢分为多个类写,看个人喜好吧,只要能实现功能就可以了;

暂时不会多线程,所以导致插入数据库数据很慢,我的解决办法是把代码编译为.exe可执行程序,然后多启动几个进程,虽然还是很慢,但是比较之前强很多;

这个只是单纯写着玩儿,如果大家要是测试数据库读、写性能的话建议使用YCSB工具。

猜你喜欢

转载自www.cnblogs.com/wuhl-89/p/10118147.html
今日推荐