creating Tables and columns dynamically using mysql python connector

家住魔仙堡 提交于 2019-12-23 05:42:10

问题


I want to create a table having columns dynamically using python list. Column Names are in the list and I want to refer them in the MySQL query. I am using MySQL.connector with python 3.4.3.

Below is the code which I tried:

col names:  ['Last Name', 'First Name', 'Job', 'Country']
table_name = 'stud_data'
query = "CREATE TABLE IF NOT EXISTS"+table_name+"("+"VARCHAR(250),".join
(col) + "Varchar(250))"
print("Query is:" ,query)
cursor.execute(query)
conn.commit()

But I am getting the following error:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name VARCHAR(250),First Name VARCHAR(250),Job VARCHAR(250),Country VARCHAR(250))' at line 1

The query looks like this:

Query is: CREATE TABLE IF NOT EXISTS stud_data (Last Name VARCHAR(250),First Name VARCHAR(250),Job VARCHAR(250),Country VARCHAR(250))

Please help on this. Thanks in advance


回答1:


You have spaces in the column name. i.e. 'First Name' instead of 'FirstName', removing the spaces will solve your problem. If you want to preserve the spaces, use backticks '`' to wrap the string

Sample code:

columns = [ ('Last Name', 'First Name', 'Job', 'Country') ] #list of tuples

for p in columns:
    q = """ CREATE TABLE IF NOT EXISTS stud_data (`{col1}` VARCHAR(250),`{col2}` VARCHAR(250),`{col3}` VARCHAR(250),`{col4}` VARCHAR(250)); """
    sql_command = q.format(col1=p[0], col2=p[1], col3=p[2], col4 = p[3])


>>> sql_command
' CREATE TABLE IF NOT EXISTS stud_data (`Last Name` VARCHAR(250),`First Name` VARCHAR(250),`Job` VARCHAR(250),`Country` VARCHAR(250)); '


来源:https://stackoverflow.com/questions/47924825/creating-tables-and-columns-dynamically-using-mysql-python-connector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!