问题
this code is not inserting my list(self.list2) into the database 'main.db'. I read the the following posts already and they all seem to use the idea of using join() to create # of place holders based on the length of the list.
Dynamically creating a placeholder to insert many column values for a row in SQLite table
Inserting to sqlite dynamically with Python 3
- the code is running without errors.
I tested the code by printing
return (f"{', '.join('?' * len(input))}")
and it prints "?, ?, ?, ? ", so I know the function works.
the database is created properly with the following code:
self.cursor.execute('''CREATE TABLE IF NOT EXISTS main (T_num text Primary Key NOT NULL, Name text NOT NULL, Item1 text, Item2 text, Item3 text)''')
Maybe I missed a small detail, or I don't know how the return statement/function works.
Please help me to trouble shoot this. Thank you for any assistance.
import tkinter as tk
import sqlite3
class Model():
def __init__(self):
self.list1 = [('Table #', '6'), ('Name', 'Jenn'), ('Beef
Tacos', '6'), ("Fish Tacos", "6")]
self.list2 = list(map(": ".join, self.list1))
self.conn = sqlite3.connect("4th.db")
self.cursor=self.conn.cursor()
self.place_holder(self.list2)
def place_holder(self, input):
return (f"{', '.join('?' * len(input))}")
self.cursor.execute("INSERT INTO main VALUES (place_holder(input))", self.list2)
self.conn.commit()
self.conn.close()
if __name__ == "__main__":
c = Model()
回答1:
You was trying to insert into db after return
in your place_holder
method which is not possible because the function exit after return. Also in your sql
specify in which column you want to insert into.
like this
self.cursor.execute(f"INSERT INTO main (T_num, Name, Item1, Item2) VALUES {_placeholder}", self.list2)
There is your complete program, hope this will help you.
import tkinter as tk
import sqlite3
class Model():
def __init__(self):
self.list1 = [('Table #', '6'), ('Name', 'Jenn'), ('Beef Tacos', '6'), ("Fish Tacos", "6")]
self.list2 = list(map(": ".join, self.list1))
self.conn = sqlite3.connect("4th.db")
self.cursor = self.conn.cursor()
_placeholder = self.place_holder(self.list2)
# specify here in which column you want to insert the data
self.cursor.execute(f"INSERT INTO main (T_num, Name, Item1, Item2) VALUES {_placeholder}", self.list2)
self.conn.commit()
self.conn.close()
def place_holder(self, input_list):
'''Returns the place holder (?, ?, .....) as string'''
return f"({', '.join('?' * len(input_list))})"
if __name__ == "__main__":
c = Model()
来源:https://stackoverflow.com/questions/59727201/python-sqlite3-record-is-not-inserting-into-the-database-with-a-placeholder-func