Python SQLite从变量插入数据

时间:2017-09-14 16:05:46

标签: python json sqlite

我正在尝试将变量的内容添加到SQLite DB中,但是我收到错误

sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

我的代码是: -

import requests
import json
import eventlet
import os
import sqlite3

#Get the currect vuln_sets
response = requests.get('https://vulners.com/api/v3/search/stats/')
vuln_set = json.loads(response.text)
vuln_type = vuln_set['data']['type_results']
for k in vuln_type:
    vuln_bulletinfamily = vuln_set['data']['type_results'][k]['bulletinFamily']
    vuln_name = vuln_set['data']['type_results'][k]['displayName']
    vuln_count = vuln_set['data']['type_results'][k]['count']



con = sqlite3.connect('vuln_sets.db')
with con:
    cur = con.cursor()
    con.row_factory = sqlite3.Row


    cur.execute("REPLACE INTO vuln_sets (vulntype, displayname, bulletinfamily, count) values (?, ?, ?, ?)", (vuln_type, vuln_bulletinfamily, vuln_name, vuln_count))
    con.commit()

变量包含JSON密钥对,因为我需要将其中的一些插入到DB中以进行处理,但是需要一个不同的项目。

堆栈跟踪是:

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    cur.execute("REPLACE INTO vuln_sets (vulntype, displayname, bulletinfamily, count) values (?, ?, ?, ?);", (vuln_type, vuln_bulletinfamily, vuln_name, vuln_count))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

1 个答案:

答案 0 :(得分:0)

@ roganjosh的评论修好了!我需要在for循环中包含数据库事务,如下所示:

import requests
import json
import eventlet
import os
import sqlite3

#Get the currect vuln_sets
response = requests.get('https://vulners.com/api/v3/search/stats/')
vuln_set = json.loads(response.text)
vuln_type = vuln_set['data']['type_results']
for k in vuln_type:
    vuln_bulletinfamily = vuln_set['data']['type_results'][k]['bulletinFamily']
    vuln_name = vuln_set['data']['type_results'][k]['displayName']
    vuln_count = vuln_set['data']['type_results'][k]['count']
    con = sqlite3.connect('vuln_sets.db')
    with con:
        cur = con.cursor()
        con.row_factory = sqlite3.Row    
        cur.execute("REPLACE INTO vuln_sets (vulntype, displayname, bulletinfamily, count) values (?, ?, ?, ?)", (k, vuln_name, vuln_bulletinfamily, vuln_count))
        con.commit()