# -*- coding: utf-8 -*-
# This does not solve the problem when processed text loaded from external file contains utf-8 encodings. This helps only for literals written in the given python script itself and is just a clue for python interpreter, but has no impact on text processing.
import sys, os.path, time, re, copy, datetime as dt, locale, codecs, random, uuid
# inclui o diretorio do projeto ao ambiente
sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
from conexao.local_conexao import py_odbc_conn
char_code = 'latin1'
print sys.stdout.encoding
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
sql_insert = u"""
INSERT INTO [sigamgeo].[TB_FIS_VISTORIAS_AIA_TCRA]
([OBJECTID]
,[NIS]
,[CaracAreaRecCL]
,[CaracAreaRecT]
,[Isolamento]
,[PerturbacoesCL]
,[PerturbacoesT]
,[Mortalidade]
,[AtaqueFormigas]
,[MatoCompeticao]
,[Riqueza]
,[AltMedMudas]
,[SubBosque]
,[PresRegen]
,[RegenNatural]
,[TecVistResp]
,[Cargo]
,[DataElabRTV]
,[DataVistoria]
,[Acompanhante1]
,[Acompanhante2]
,[Conclusao]
,[StatusVistoria]
,[Metodologia]
,[Relatorio]
,[RecomTec]
,[PSMA]
,[HistMax]
,[ObsAdicMax]
,[MudasPlantadas]
,[AreaDano_ha]
,[GlobalID])
VALUES
({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11},
{12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22},
{23}, {24}, {25}, {26}, {27}, {28}, {29}, {30}, {31});
"""
sql_select = u"""
SELECT [OBJECTID] --0
,[NIS] --1
,[CaracAreaRecCL] --2
,[CaracAreaRecT] --3
,[Isolamento] --4
,[PerturbacoesCL] --5
,[PerturbacoesT] --6
,[Mortalidade] --7
,[AtaqueFormigas] --8
,[MatoCompeticao] --9
,[Riqueza] --10
,[AltMedMudas] --11
,[SubBosque] --12
,[PresRegen] --13
,[RegenNatural] --14
,[TecVistResp] --15
,[Cargo] --16
,[DataElabRTV] --17
,[DataVistoria] --18
,[Acompanhante1] --19
,[Acompanhante2] --20
,[Conclusao] --21
,[StatusVistoria] --22
,[Metodologia] --23
,REPLACE(CONVERT(NVARCHAR(MAX), [Relatorio]), '''', '''''') --24 dobra aspas simples p/ sql server reconhecer como texto
,CONVERT(NVARCHAR(MAX), [RecomTec]) --25
,[PSMA] --26
,CONVERT(NVARCHAR(MAX), [HistMax]) --27
,CONVERT(NVARCHAR(MAX), [ObsAdicMax]) --28
,[MudasPlantadas] --29
,[AreaDano_ha] --30
,'GlobalID' AS GlobalId --31
FROM TB_VISTORIAS_AIA_TCRA
WHERE DataVerifSigam IS NULL;
"""
print "{} - Iniciando conexao ao spatialdata".format(time.strftime("%x %X"))
odbc_spatialdata = py_odbc_conn('sql01', 'spatialdata', 'geodataowner', '@@X.y.z.1')
registros = odbc_spatialdata.cursor().execute(sql_select).fetchall() #tuple com todos os registros
print "{} - Iniciando loop de insert".format(time.strftime("%x %X"))
if registros <> None:
for registro in registros:
try:
reg = list(registro) #tuple para list
registro_encoded = [] #lista que ira receber o registro tratado
for v in reg: #loop dentro da lista do registro
if v == reg[24] and v <> None: #trata relatorio para insert
registro_encoded.append("'" + v + "'")
elif v == reg[18]: #trata DataVistoria
data = str(v)
registro_encoded.append("'" + data + "'")
elif v == reg[31]: #gera globalId para insert
gid = '{' + str(uuid.uuid4()) + '}'
registro_encoded.append("'" + gid + "'")
elif (isinstance(v, str) or isinstance(v, unicode)):
p = re.compile("('|\'|\?)")
v = p.sub(" ",v)
registro_encoded.append(u"'" + v.decode(char_code, 'replace') + u"'")
elif(isinstance(v, int) or isinstance(v, float)):
registro_encoded.append(v)
elif(not isinstance(v, int) and not isinstance(v, float) and not isinstance(v, object)
or unicode(v) =='None' ):
registro_encoded.append('NULL')
else:
registro_encoded.append(unicode(v))
cursor = odbc_spatialdata.cursor().execute(sql_insert.format(*registro_encoded))
cursor.commit()
except Exception as e:
print e
print "{} - Encerrando conexao ao spatialdata".format(time.strftime("%x %X"))
odbc_spatialdata.close()
dataHoje = dt.datetime.now()
dataString = str(dataHoje)
dataVerif = dataString[:-7]
print dataVerif
print 'Fim'
# This does not solve the problem when processed text loaded from external file contains utf-8 encodings. This helps only for literals written in the given python script itself and is just a clue for python interpreter, but has no impact on text processing.
import sys, os.path, time, re, copy, datetime as dt, locale, codecs, random, uuid
# inclui o diretorio do projeto ao ambiente
sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
from conexao.local_conexao import py_odbc_conn
char_code = 'latin1'
print sys.stdout.encoding
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
sql_insert = u"""
INSERT INTO [sigamgeo].[TB_FIS_VISTORIAS_AIA_TCRA]
([OBJECTID]
,[NIS]
,[CaracAreaRecCL]
,[CaracAreaRecT]
,[Isolamento]
,[PerturbacoesCL]
,[PerturbacoesT]
,[Mortalidade]
,[AtaqueFormigas]
,[MatoCompeticao]
,[Riqueza]
,[AltMedMudas]
,[SubBosque]
,[PresRegen]
,[RegenNatural]
,[TecVistResp]
,[Cargo]
,[DataElabRTV]
,[DataVistoria]
,[Acompanhante1]
,[Acompanhante2]
,[Conclusao]
,[StatusVistoria]
,[Metodologia]
,[Relatorio]
,[RecomTec]
,[PSMA]
,[HistMax]
,[ObsAdicMax]
,[MudasPlantadas]
,[AreaDano_ha]
,[GlobalID])
VALUES
({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11},
{12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22},
{23}, {24}, {25}, {26}, {27}, {28}, {29}, {30}, {31});
"""
sql_select = u"""
SELECT [OBJECTID] --0
,[NIS] --1
,[CaracAreaRecCL] --2
,[CaracAreaRecT] --3
,[Isolamento] --4
,[PerturbacoesCL] --5
,[PerturbacoesT] --6
,[Mortalidade] --7
,[AtaqueFormigas] --8
,[MatoCompeticao] --9
,[Riqueza] --10
,[AltMedMudas] --11
,[SubBosque] --12
,[PresRegen] --13
,[RegenNatural] --14
,[TecVistResp] --15
,[Cargo] --16
,[DataElabRTV] --17
,[DataVistoria] --18
,[Acompanhante1] --19
,[Acompanhante2] --20
,[Conclusao] --21
,[StatusVistoria] --22
,[Metodologia] --23
,REPLACE(CONVERT(NVARCHAR(MAX), [Relatorio]), '''', '''''') --24 dobra aspas simples p/ sql server reconhecer como texto
,CONVERT(NVARCHAR(MAX), [RecomTec]) --25
,[PSMA] --26
,CONVERT(NVARCHAR(MAX), [HistMax]) --27
,CONVERT(NVARCHAR(MAX), [ObsAdicMax]) --28
,[MudasPlantadas] --29
,[AreaDano_ha] --30
,'GlobalID' AS GlobalId --31
FROM TB_VISTORIAS_AIA_TCRA
WHERE DataVerifSigam IS NULL;
"""
print "{} - Iniciando conexao ao spatialdata".format(time.strftime("%x %X"))
odbc_spatialdata = py_odbc_conn('sql01', 'spatialdata', 'geodataowner', '@@X.y.z.1')
registros = odbc_spatialdata.cursor().execute(sql_select).fetchall() #tuple com todos os registros
print "{} - Iniciando loop de insert".format(time.strftime("%x %X"))
if registros <> None:
for registro in registros:
try:
reg = list(registro) #tuple para list
registro_encoded = [] #lista que ira receber o registro tratado
for v in reg: #loop dentro da lista do registro
if v == reg[24] and v <> None: #trata relatorio para insert
registro_encoded.append("'" + v + "'")
elif v == reg[18]: #trata DataVistoria
data = str(v)
registro_encoded.append("'" + data + "'")
elif v == reg[31]: #gera globalId para insert
gid = '{' + str(uuid.uuid4()) + '}'
registro_encoded.append("'" + gid + "'")
elif (isinstance(v, str) or isinstance(v, unicode)):
p = re.compile("('|\'|\?)")
v = p.sub(" ",v)
registro_encoded.append(u"'" + v.decode(char_code, 'replace') + u"'")
elif(isinstance(v, int) or isinstance(v, float)):
registro_encoded.append(v)
elif(not isinstance(v, int) and not isinstance(v, float) and not isinstance(v, object)
or unicode(v) =='None' ):
registro_encoded.append('NULL')
else:
registro_encoded.append(unicode(v))
cursor = odbc_spatialdata.cursor().execute(sql_insert.format(*registro_encoded))
cursor.commit()
except Exception as e:
print e
print "{} - Encerrando conexao ao spatialdata".format(time.strftime("%x %X"))
odbc_spatialdata.close()
dataHoje = dt.datetime.now()
dataString = str(dataHoje)
dataVerif = dataString[:-7]
print dataVerif
print 'Fim'
Nenhum comentário:
Postar um comentário