[英]Python - Inserting dictionary into SQLite3
I got a dictionary with 14 keys.我有一本有 14 个键的字典。
First Ive created createTableOfRecordsenter
function:首先我创建了createTableOfRecordsenter
function:
def createTableOfRecords(self):
create_table = '''CREATE TABLE IF NOT EXISTS records(Budget TEXT , Commitment TEXT, Contract_Type TEXT , Customer_Type TEXT, Duration TEXT , Goals TEXT, Pace TEXT ,
Procedures_and_Regulations TEXT, Resources TEXT , Scope TEXT, Team_Availability TEXT , Team_Distribution TEXT, Team_Size TEXT , Uncertainty TEXT);'''
self.cursor.execute(create_table)
self.connection.commit()
and the table with columns created successfully.以及成功创建列的表。 After that, I tried to insert the data using the insertRecords
function:之后,我尝试使用insertRecords
function 插入数据:
global var_dict
var_dict = dict(Budget="Fixed",
Commitment="Low",
Contract_Type="Hybrid",
Customer_Type="Market",
Duration="Long",
Goals="Unclear",
Pace="Fast",
Procedures_and_Regulations="None",
Resources="Standart",
Scope="Rigid",
Team_Availability="Fully",
Team_Distribution="Global",
Team_Size="Small",
Uncertainty="Predictable")
def insertRecords(self):
self.cursor.execute('INSERT INTO records (Budget,Commitment,Contract_Type,Customer_Type,Duration,Goals,Pace,'
'Procedures_and_Regulations,Resources,Scope,Team_Availability,'
'Team_Distribution,Team_Size,Uncertainty) '
'VALUES (:Budget, :Commitment, :Contract_Type, :Customer_Type, :Duration, '
':Goals, :Pace, :Procedures_and_Regulations, :Resources, :Scope, :Team_Availability, '
':Team_Distribution, :Team_Size, :Uncertainty);'), var_dict
self.connection.commit()
but I didn't get any value inserted into the database table.但我没有将任何值插入到数据库表中。 I got this error message:我收到此错误消息:
self.cursor.execute('INSERT INTO records (Budget,Commitment,Contract_Type,Customer_Type,Duration,Goals,Pace,' sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 14, and there are 0 supplied.
Does anyone know what I've done wrong?有谁知道我做错了什么? Thanks!谢谢!
You've written:你写过:
self.cursor.execute( 'insert ...' ), var_dict
var_dict
is not being passed as an argument to execute
. var_dict
没有作为参数传递给execute
。 It is outside the parenthesis.它在括号外。 Instead you are making a two element tuple of the result of execute
and var_dict
and then throwing it out.相反,您正在制作execute
和var_dict
的结果的两个元素元组,然后将其丢弃。
You want to pass var_dict into execute like so.您想像这样将 var_dict 传递给执行。
self.cursor.execute( 'insert ...', var_dict )
Here's a quick illustration of the difference.这是差异的快速说明。
>>> var_dict = dict(foo="bar")
>>> def test(sql, *optional):
... print(f"Got sql '{sql}' and args {optional}\n")
...
>>> test('insert...'), var_dict
Got sql 'insert...' and args ()
(None, {'foo': 'bar'})
>>> test('insert...', var_dict)
Got sql 'insert...' and args ({'foo': 'bar'},)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.