简体   繁体   English

如何从列表创建sqlite3表列? (在python中)

[英]How to create sqlite3 table columns from a list? (in python)

I'm trying to build a table columns according to a user request (the size of the list may change, that's why I can't determine an exact number of question marks): 我正在尝试根据用户请求构建表列(列表的大小可能会改变,这就是为什么我无法确定确切数量的问号的原因):

userInput=[a,b,c,d,e,f,g]
ct.execute('CREATE TABLE IF NOT EXISTS chars(?)',(userInput))

I get the following error: 我收到以下错误:

sqlite3.OperationalError: near "?": syntax error

To answer your question, we will ignore security issues. 为了回答您的问题,我们将忽略安全问题。 I assume you want to create (untyped) columns according to your python list. 我假设您想根据您的python列表创建(无类型)列。

CREATE TABLE chars (a,b,c,d,e,f,g)

Here is my proposal: 这是我的建议:

userInput=['a','b','c','d','e','f','g']
q = "CREATE TABLE IF NOT EXISTS chars(%s)" % ", ".join(userInput)

(Note that the column names must be quoted, per the Python syntax of string literals). (请注意,必须按照字符串文字的Python语法用引号引起来)。

It may be argued that %s as a syntax is "de-emphasized", but in my humble opinion it is nicely terse in that case. 也许有人争辩说%s作为一种语法是“不加强调的”,但在我的拙见中,在这种情况下,它非常简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM