Jump to content

TecInfo

Membros
  • Contagem de Conteúdo

    8
  • Ingressou

  • Última visita

Clientes & Parceiros

  • Você é um cliente TecnoSpeed?
    Não
  • Você é um parceiro da Casa do Desenvolvedor?
    Não

Conquistas de TecInfo

  • Positividade Raro

Emblemas Recentes

1

Reputação na Comunidade

  1. Resolvido. while cliente['hasNext'] == True: valoresInserir = [] nPage = nPage + 1 request = requests.get('http://srv009:8080/api/cdp/v1/getCliente?page=' + str(nPage) + '&pageSize=100', auth=('userapi', 'xxxxx')) cliente = request.json() comandoSQL = 'INSERT INTO cliente (clienteID, nomeAbrev, nome) VALUES (%s, UPPER(%s), UPPER(%s))' for clientes in cliente['items']: valoresInserir.append((clientes['clienteId'], clientes['nomeAbrev'], clientes['nome'])) cursor.executemany(comandoSQL,valoresInserir) conexao.commit()
  2. Bom dia, Eu estou desenvolvendo um programa que grava os dados vindo JSON no banco MySQL, mas está gerando o seguinte erro. Traceback (most recent call last): File "c:\Projetos\api\getCliente\getClienteMySQL.py", line 58, in <module> cursor.executemany(comandoSQL,valoresInserir) File "C:\Python310\lib\site-packages\mysql\connector\cursor_cext.py", line 375, in executemany self.execute(operation, params) File "C:\Python310\lib\site-packages\mysql\connector\cursor_cext.py", line 271, in execute raise ProgrammingError( mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement [Done] exited with code=1 in 2.222 seconds Trecho do código: while cliente['hasNext'] == True: valoresInserir = [] nPage = nPage + 1 request = requests.get('http://srv009:8080/api/cdp/v1/getCliente?page=' + str(nPage) + '&pageSize=100', auth=('userapi', '1q2w!Q@WAPIpw')) cliente = request.json() for clientes in cliente['items']: valoresInserir.append((clientes['clienteId'], clientes['nomeAbrev'], clientes['nome'])) comandoSQL = f'INSERT INTO cliente (clienteID, nomeAbrev, nome) VALUES (?, UPPER(?), UPPER(?))' cursor.executemany(comandoSQL,valoresInserir) conexao.commit()
  3. @Thanael, resolvi da seguinte forma. valoresInserir = [] for clientes in cliente['items']: valoresInserir.append((clientes['clienteId'], clientes['nomeAbrev'], clientes['nome'])) comandoSQL = "INSERT INTO cliente (cliente_id, nome_abrev, nome) VALUES (?, ?, ?)" cursor.executemany(comandoSQL, valoresInserir) Muito obrigado pela ajuda.
  4. Segue um trecho do JSON. [{"clienteId": 0, "nomeAbrev": "PEF", "nome": "PAGAMENTO EXTRA FORNECEDOR"}]
  5. Não deu certo. for cliente in jsonString: clienteId = int(cliente['clienteId']) nomeAbrev = cliente['nomeAbrev'] nome = cliente['nome'] comandoSQL = f"INSERT INTO cliente (cliente_id, nome_abrev, nome) VALUES ({clienteId}, {nomeAbrev}, {nome})" cursor.execute(comandoSQL) conexao.commit() File "c:\Projetos\api\getCliente.py", line 25, in <module> clienteId = int(cliente['clienteId']) TypeError: string indices must be integers
  6. Boa tarde, @Thanael, usando a segunda opção, gerou o erro abaixo. C:/Python310/python.exe c:/Projetos/api/getCliente.py Traceback (most recent call last): File "c:\Projetos\api\getCliente.py", line 25, in <module> clienteId = cliente['clienteId'] TypeError: string indices must be integers
  7. Boa tarde, @thanael Usando o pandas deu os seguintes erros. C:/Python310/python.exe c:/Projetos/api/getClienteV2.py C:\Python310\lib\site-packages\pandas\io\sql.py:761: UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy warnings.warn( Traceback (most recent call last): File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 2020, in execute cur.execute(*args, **kwargs) pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\Projetos\api\getClienteV2.py", line 26, in <module> df.to_sql('cliente',conexao,index=False,if_exists='append') File "C:\Python310\lib\site-packages\pandas\core\generic.py", line 2951, in to_sql return sql.to_sql( File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 697, in to_sql return pandas_sql.to_sql( File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 2189, in to_sql table.create() File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 831, in create if self.exists(): File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 815, in exists return self.pd_sql.has_table(self.name, self.schema) File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 2197, in has_table return len(self.execute(query, [name]).fetchall()) > 0 File "C:\Python310\lib\site-packages\pandas\io\sql.py", line 2032, in execute raise ex from exc pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
  8. Olá pessoal, eu sou novo em Python e novo aqui no fórum. Eu estou desenvolvendo um programa em Python que acessa uma API, essa API retorna um JSON e esse retorno eu tenho que gravar em um banco de dados SQL. O acesso a API está OK, o problema é gravar no banco. Segue o código fonte que estou usando. from optparse import Values from turtle import st from urllib import request import requests import pyodbc import json import textwrap request = requests.get('http://SRVAPI:8280/api/cdp/v1/getCliente') addressData = request.json() jsonString = json.dumps(addressData['items']) server = 'SRVBanco' dataBase = 'DWSimu' userName = 'sa' passWord = 'senha' conexao = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+dataBase+';UID='+userName+';PWD='+ passWord) cursor = conexao.cursor() valoresInserir = [] for cliente in jsonString: clienteId = cliente['clienteId'] nomeAbrev = cliente['nomeAbrev'] nome = cliente['nome'] linhaInserir = (clienteId, nomeAbrev, nome) valoresInserir.append(linhaInserir) comandoSQL = "INSERT INTO cliente (cliente_id, nome_abrev, nome) VALUES (%s, %s, %s)" cursor.executemany(comandoSQL, valoresInserir) conexao.commit() cursor.close() conexao.close() Segue o erro que é retornado. Traceback (most recent call last): File "c:\Projetos\api\getCliente.py", line 25, in <module> clienteId = cliente['clienteId'] TypeError: string indices must be integers Um detalhe, o campo clienteId é inteiro
×
×
  • Create New...