python sqlite3记录未使用占位符函数插入数据库 [英] python sqlite3 record is not inserting into the database with a placeholder function
问题描述
这段代码没有将我的列表(self.list2)插入到数据库main.db"中.我已经阅读了以下帖子,它们似乎都使用了使用 join() 根据列表长度创建 # 个占位符的想法.
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.
- 代码运行没有错误.
我通过打印来测试代码
- 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)''')
也许我漏掉了一个小细节,或者我不知道 return 语句/函数是如何工作的.
请帮我解决这个问题.感谢您提供任何帮助.
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()
推荐答案
您试图在 place_holder
方法中的 return
之后插入到 db 中,这是不可能的,因为函数返回后退出.同样在您的 sql
中指定要插入的列.像这样
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()
这篇关于python sqlite3记录未使用占位符函数插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!