Python中sqlite3错误提示.InterfaceError

Python中sqlite3错误提示:
图片描述

代码如下:

df = pandas.DataFrame(newsdetail)
df.to_excel('news1.xls')
import sqlite3
with sqlite3.connect('news.sqlite') as db:
    df.to_sql('news',con = db)
    df2 = pandas.read_sql_query('SELECT * FROM news',con = db)
print(df2)    

请问问题出在哪里?刚接触Python,看着教程原封不动翘出来的代码。

阅读 7.7k
2 个回答

根据 @剑心无痕 的答案提示,终于找到出现这种错误的原因。
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
出现这个错误是应为

df = pandas.DataFrame(newsdetail)

newsdetail(一个字典列表)其中一个字典的值是列表,所以会提示出错。如果把列表换成字符串就会正常。

import pandas
import sqlite3
df = pandas.DataFrame([{'1':2}, {'3':4}])
with sqlite3.connect('news.sqlite') as db:
    df.to_sql('news',con = db)
    df2 = pandas.read_sql_query('SELECT * FROM news',con = db)
# 正常插入


df = pandas.DataFrame([{'1':{1:2}}, {'3':{3:4}}])
with sqlite3.connect('news.sqlite') as db:
    df.to_sql('news1',con = db)
    df2 = pandas.read_sql_query('SELECT * FROM news',con = db)
# sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type报错不支持的类型
df['1'] 是object类型无法装换


df = pandas.DataFrame([1, '2'])
with sqlite3.connect('news.sqlite') as db:
    df.to_sql('news2',con = db)
    df2 = pandas.read_sql_query('SELECT * FROM news',con = db)
df[0] 是object类型正常插入 因为可以转换成字符串
cur = db.execute('select * from sqlite_master WHERE type="table" and name= "news2"')
print(cur.fetchone()) # ('table', 'news2', 'news2', 6, 'CREATE TABLE "news2" (\n"index" INTEGER,\n  "0" TEXT\n)') 转换成字符串TEXT了
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题