import sys
import pymysql
import os
from timeit import default_timer as timer
from datetime import timedelta
def my_function(x):
print(x)
query = f"""
SELECT
u.id_user,
u.first_name,
u.last_name,
u.cpf,
p.id_phone,
p.id_user,
p.phone_type,
p.phone_number
FROM
datatomongo.user as u
LEFT JOIN
datatomongo.phone as p
ON
u.id_user = p.id_user
;
"""
MYDB = pymysql.connect(host="127.0.0.1",user="root",password="",database="")
MYCURSOR = MYDB.cursor() if pymysql.connect(host="127.0.0.1",user="root",password="",database="") else os.exit(1)
sql = query
print ("Carregando sql->" + sql)
print(f"Início da execução BUSCADB no bd")
start = timer()
MYCURSOR.execute(sql)
result = MYCURSOR.fetchall()
#print(result)
MYCURSOR.close()
MYDB.close()
end = timer()
print(f'tempo necessário da execução BUSCADB {len(result)} {timedelta(seconds=end-start)}')
insert_json =[]
insert_json.append("[\n")
id_user = ''
first_name = ''
last_name = ''
cpf = ''
id_kpi = ''
turn = False
print("Início da execução CRIAÇÃO INSERT no bd MONGO")
start = timer()
if result != '':
for dados in result:
if id_user != dados[0] or first_name != dados[1] or last_name != dados[2] or cpf != dados[3]:
if id_user != '':
insert_json[-1] =insert_json[-1][:-2]
insert_json.append( "\n")
insert_json.append( " ]\n")
insert_json.append( " },\n")
id_user = dados[0]
first_name = dados[1]
last_name = dados[2]
cpf = dados[3]
insert_json.append( " {\n")
insert_json.append( ' "first_name":"{}",\n'.format(first_name))
insert_json.append( ' "last_name":"{}",\n'.format(last_name))
insert_json.append( ' "cpf":"{}",\n'.format(cpf))
insert_json.append( ' "vector_phone": [\n')
turn = False
insert_json.append( " {")
insert_json.append( '"phone_type": "{}","phone_number": "{}"'.format(dados[6],dados[7]))
insert_json.append( "},\n")
turn = True
insert_json.append( " ]\n")
insert_json.append( " }\n")
insert_json.append("]")
else:
print("insert vazio")
return
end = timer()
##print('tempo necessário da execução CRIAÇÃO insert_json {}'.format(timedelta(seconds=end-start)))
insert_json="".join(insert_json)
with open(f'InsertMongo.json', 'w') as f:
## print (insert_usn)
f.write(insert_json)
end = timer()
def main():
my_function(x = 3)
if __name__ == "__main__":
main()