将文件中的数据通过python传到mysql中 | 您所在的位置:网站首页 › python下载数据库文件 › 将文件中的数据通过python传到mysql中 |
我们需要几个包来实现这一功能,下面我和详细讲一下这几个包 一、pymysql要传数据到数据库中肯定先要连接数据库 ①连接数据库 db = pymysql.connect('localhost', 'root', '000000', 'sys') # 等价于,因为怕参数顺序错误,可以通过以下形式 db = pymysql.connect(host='localhost', user='root', password='000000', database='sys') # 等价于,也可以将参数都传到一个字典里,作为参数传递给函数 DATABASE = { 'host': 'localhost', 'database': 'girls', 'user': 'root', 'password': '000000' } db = pymysql.connect(**DATABASE)下面是连接数据库connect的所有参数,大家写的时候可以参考一下 要完成一个MySQL数据的连接,在connect中可以接受以下参数 host=None, user=None, password="", database=None, port=0, unix_socket=None, charset='', sql_mode=None, read_default_file=None, conv=None, use_unicode=None, client_flag=0, cursorclass=Cursor, init_command=None, connect_timeout=10, ssl=None, read_default_group=None, compress=None, named_pipe=None, no_delay=None, autocommit=False, db=None, passwd=None, local_infile=False, max_allowed_packet=16*1024*1024, defer_connect=False, auth_plugin_map={}, read_timeout=None, write_timeout=None, bind_address=None host表示主机名;user表示用户名;password表示密码; database表示指定的数据库;port表示端口号,默认3306; charset表示指定字符编码(utf8mb4相当于utf-8) ②连接到了数据库之后,就是对数据库进行增删改:首先要定义一个游标cursor,通过游标来操作数据库,别忘了操作完后要关闭游标 cursor = db.cursor() sql = 'select * from beauty' # 要执行的sql语句 # 执行sql语句 cursor.execute(sql) db.commit() # 若操作数增删改则需要提交数据 若为查询语句,得到数据后要打印数据需要用到fetchall函数 cursor = db.cursor() sql = 'select * from beauty' # 要执行的sql语句 # 执行sql语句 cursor.execute(sql) # 将执行的结果传递给data,为字符串形式 data = cursor.fetchall() for row in data: print(row)结果: 若要知道数据对应的是哪列可以用进阶的方法: cursor = db.cursor() sql = 'select * from beauty' # 要执行的sql语句 # 默认情况下,我们获取到的返回值是元组,只能看到每行的数据, # 却不知道每一列代表的是什么,这个时候可以使用以下方式来返回字典,每一行的数据都会生成一个字典: # 在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor cursor = db.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql) data = cursor.fetchall() for row in data: print(row)结果: ![]() 粗略来说文件可以分为3种:文本文件、二进制文件和大文件 python操作文件是用open函数,其打开试试默认以文本文件形式打开的但是open函数默认编码是None,所以处理文本文件时,要指定其文件编码 ①读取小文件 file_name = 'demo2.txt' try: with open(file_name, encoding='utf-8') as file_obj: content = file_obj.read(6) content = file_obj.read(6) content = file_obj.read(6) content = file_obj.read(6) except FileNotFoundError : print(f'{file_name} 这个文件不存在!')read的几点注意事项: 通过read来读取文件,但直接调用read()它会将文本文件的所有内容全部都读取出来,所以如果要读取的文件较大的话,会一次性将文件的内容加载到内存中,容易导致内存泄漏,所以对于较大的文件,不要直接调用read()。 要打印数据时,read()可以接收一个size作为参数,该参数用来指定要读取的字符的数量,默认值为-1,它会读取文件中的所有字符,每一次读取都是从上次读取到位置开始读取的,如果字符的数量小于size,则会读取剩余所有的,如果已经读取到了文件的最后了,则会返回''空串 结果: readline():该方法可以用来读取一行内容 readlines():该方法用于一行一行的读取内容,它会一次性将读取到的内容封装到一个列表中返回 file_name = 'demo.txt' with open(file_name, encoding='utf-8') as file_obj: print(file_obj.readline(), end='') r = file_obj.readlines() pprint.pprint(r[0])且注意:readline读过的数据readlines不会再读了,反过来也是一样 结果: 结果: 结果: 首先肯定是要先构件表啦! 中间是要将文件中的数据加工成你想要的数据 import pymysql import time file_name = "D:\\桌面\\part-r-00000" DATABASE = { 'host': 'localhost', 'database': 'text_exc', 'user': 'root', 'password': '000000' } db = pymysql.connect(**DATABASE) with open(file_name, encoding='utf-8') as file_obj: r = file_obj.readlines() try: for t in r: line = t.split(",") line.append(time.mktime(time.strptime(line[0], "%Y%m%d%H%M%S"))) line[0] = line[0][0:4] + "-" + line[0][4:6] + "-" + line[0][6:8] + " " + line[0][8:10] + ":" \ + line[0][10:12] + ":" + line[0][12:14] line[4] = line[4][:-1] sql = f"insert into traffic value ('{line[1]}', '{line[0]}', '{line[2]}', {float(line[3])}," \ f" {float(line[4])}, {line[5]})" my_cursor = db.cursor() my_cursor.execute(sql) except Exception as e: print(e) finally: if my_cursor is not None: try: my_cursor.close() # 关闭游标 except Exception as e: print(e) try: db.commit() # 提交数据 db.close() # 关闭数据库 except Exception as e: print(e)
|
CopyRight 2018-2019 实验室设备网 版权所有 |