Я пытался получить данные по URL-ссылке и сохранить их в файле базы данных. Когда я преобразовал извлеченные данные в dataframe и вставил их в таблицу, я получил сообщение об ошибке «sqlite3.InterfaceError: Ошибка привязки параметра 1 - возможно, неподдерживаемый тип».
Вот мой код:
import pandas as pd
import requests
import sqlite3
from pandas.io import sql
database_file = 'z5192421.db'
def if_table_exist(cnx,table_name):
c = cnx.cursor()
c.execute(f"SELECT name FROM sqlite_master WHERE type = 'table' AND
name='{table_name}'")
return c.fetchone()
def write_in_sqlite(dataframe, database_file, table_name):
cnx = sqlite3.connect(database_file)
c = cnx.cursor()
if not if_table_exist(cnx, table_name):
sql.to_sql(dataframe, name=table_name, con=cnx)
else:
for index, row in dataframe.iterrows():
values = '('+','.join(['?']*len(dataframe.columns))+')'
c.execute(f'INSERT INTO {table_name} VALUES {values}',
tuple(row.values))
def post():
url = 'http://api.worldbank.org/v2/countries/all/indicators/' \
'NY.GDP.MKTP.CD?date=2012:2017&format=json&per_page=1000'
data = requests.get(url).json()[1]
dfItem = pd.DataFrame.from_records(data)
write_in_sqlite(dfItem,database_file, 'DATA')
post()
И обратная связь:
Traceback (most recent call last):
File "/Users/chenhao/PycharmProjects/untitled/9321/post_to_stack.py", **line 34, in <module>
post()**
File "/Users/chenhao/PycharmProjects/untitled/9321/post_to_stack.py", **line 32, in post
write_in_sqlite(dfItem,database_file, 'DATA')**
File "/Users/chenhao/PycharmProjects/untitled/9321/post_to_stack.py", **line 19, in write_in_sqlite
sql.to_sql(dataframe, name=table_name, con=cnx,index = False)**
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/io/sql.py", **line 512, in to_sql
pandas_sql.to_sql(**
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/io/sql.py", **line 1734, in to_sql
table.insert(chunksize, method)**
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/io/sql.py", **line 755, in insert
exec_insert(conn, keys, chunk_iter)**
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/io/sql.py", **line 1464, in _execute_insert
conn.executemany(self.insert_statement(), data_list)**
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.