鍍金池/ 問(wèn)答/Python  數(shù)據(jù)庫(kù)/ Python中sqlite3錯(cuò)誤提示.InterfaceError

Python中sqlite3錯(cuò)誤提示.InterfaceError

Python中sqlite3錯(cuò)誤提示:
圖片描述

代碼如下:

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)    

請(qǐng)問(wèn)問(wèn)題出在哪里?剛接觸Python,看著教程原封不動(dòng)翹出來(lái)的代碼。

回答
編輯回答
尐潴豬

根據(jù) @劍心無(wú)痕 的答案提示,終于找到出現(xiàn)這種錯(cuò)誤的原因。
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
出現(xiàn)這個(gè)錯(cuò)誤是應(yīng)為

df = pandas.DataFrame(newsdetail)

newsdetail(一個(gè)字典列表)其中一個(gè)字典的值是列表,所以會(huì)提示出錯(cuò)。如果把列表?yè)Q成字符串就會(huì)正常。

2018年3月23日 18:11
編輯回答
乖乖噠
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報(bào)錯(cuò)不支持的類(lèi)型
df['1'] 是object類(lèi)型無(wú)法裝換


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類(lèi)型正常插入 因?yàn)榭梢赞D(zhuǎn)換成字符串
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)') 轉(zhuǎn)換成字符串TEXT了
2017年3月21日 03:14