使用mysql python连接器动态创建表和列 [英] creating Tables and columns dynamically using mysql python connector

查看:178
本文介绍了使用mysql python连接器动态创建表和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python列表动态创建具有列的表.列名在列表中,我想在MySQL查询中引用它们.我正在将MySQL.connector与python 3.4.3一起使用.

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()

但是我遇到以下错误:

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

查询如下:

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

推荐答案

列名中有空格. 即使用名字"而不是名字",删除空格将解决您的问题. 如果要保留空格,请使用反引号'`'来包装字符串

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

示例代码:

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)); '

这篇关于使用mysql python连接器动态创建表和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆