[英]How can I create SQL table keys with items from looping through a list in Python
I have a list called headers
of about 40-50 items, and I'm trying to make them all keys in a table.我有一个名为
headers
的列表,其中包含大约 40-50 个项目,我正试图将它们全部设为表中的键。 I'm trying to avoid typing them all out, here's what I have so far:我试图避免将它们全部输入,这是我到目前为止的内容:
def createtable_db():
cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')
mycursor = cnx.cursor()
create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"
for h in headers:
pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
mycursor.execute(create_table)
mycursor.execute(pop_table)
cnx.close()
createtable_db()
This only adds the very last key, I tried adding a + to make this line:这只添加了最后一个键,我尝试添加一个 + 来制作这一行:
pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
but that's also not working: it gives me a syntax error.但这也不起作用:它给了我一个语法错误。
The following demonstrative code is for generating a pop_table
string as a sequence of ALTER TABLE
SQL commands, one for each column to be added.以下演示代码用于将
pop_table
字符串生成为一系列ALTER TABLE
SQL 命令,每个要添加的列一个。 You can你可以
ADD columnName column format
ADD columnName column format
headers
headers
的每个元素的列数据部分填充它join
them to build the complete sequence of queries. join
他们以构建完整的查询序列。 ADD
sections have to be separated by commas ,
ADD
部分必须用逗号分隔,
ALTER TABLE
. ALTER TABLE
。 The query is terminated by a semicolon ;
;
headers = [ "Stack22", "overflow22", "rules22"]
header_columns_commands =[]
for h in headers:
header_columns_commands .append("ADD "+ h +" VARCHAR(255)")
pop_table = "ALTER TABLE players " + ",".join(header_columns_commands ) + ";"
print(pop_table)
Output: Output:
ALTER TABLE players
ADD Stack VARCHAR(255),
ADD overflow VARCHAR(255),
ADD rules VARCHAR(255);
Tested on MySQL.在 MySQL 上测试。
Try initializing pop_table
to an empty string and then concatenating to it, inside of the for loop.尝试将
pop_table
初始化为一个空字符串,然后在 for 循环内连接到它。
pop_table = ''
for h in headers:
pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
You could also initialize it to an empty list and append the generated strings您还可以将其初始化为一个空列表和 append 生成的字符串
pop_table = []
for h in headers:
pop_table.append("ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)")
# join them with you choice of delimiter
joined_up = ','.join(pop_table)
pop_table = "ALTER TABLE players "
for h in headers:
pop_table += "ADD COLUMN "+ h + " VARCHAR(255), "
#Replace the last , with a ;
pop_table.replace(pop_table[len(pop_table)-1], ';')
mycursor.execute(create_table)
mycursor.execute(pop_table, multi=True)
Maybe if you did it like this?也许如果你这样做了? Sorry its been a while since I used
mysql.connector
.抱歉,自从我使用
mysql.connector
以来已经有一段时间了。 If I remember correctly, multi
must be set to True
if you intend to execute more than one command.如果我没记错的话,如果您打算执行多个命令,则必须将
multi
设置为True
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.