如何使用每个列名及其数据类型创建SQL查询

时间:2017-10-19 17:50:25

标签: python mysql

我有一个包含2列的CSV文件:数据库的列名及其数据类型。我希望编写一个python代码,用于创建每个列名称及其数据类型的SQL查询。之前我使用的代码将每种数据类型概括为varchar 大约有100列。 这里需要一些想法..

# for every column in the list of columns
for i in range(number_of_columns):
    # if it is any column other than the last column
    if i != number_of_columns-1:
        # comma after every column
        CREATE_TABLE_SQL_QUERY += "%s VARCHAR(50)," %(header_list[i])
    # if it is the last column
    else:
        # no comma after last column
        CREATE_TABLE_SQL_QUERY += "%s VARCHAR(50))" %(header_list[i])

# prints the SQL query the needs to be executed for this file's table 
print(CREATE_TABLE_SQL_QUERY)

2 个答案:

答案 0 :(得分:0)

如何创建(a)与column_names对应的类型列表,或者(B)创建(column_name,column_type)元组列表?

您可以使用此生成SQL Query / DDL。

使用方法B的示例:

table_schema = [("ID", "int"), ("NAME", "VARCHAR(50)"), ("NICKNAME", "VARCHAR(50)")]

DDL = ','.join(('{name} {type}'.format(name=col_name, type=col_type) for (col_name, col_type) in table_schema))

生成的DDL字符串如下所示:

'ID int,NAME VARCHAR(50),NICKNAME VARCHAR(50)'

使用现有数据集(2列csv),您可以构建(col_name,col_type)对的table_schema列表并应用此方法。

答案 1 :(得分:0)

如果你的csv如下(table_schema.csv):

name, type
Setting, text
Value, integer

你可以使用csv模块

或多或少地使用这样的东西
import csv

with open('table_schema.csv', 'rt', encoding='utf-8') as f:
    sql_parts = [] 
    headers = ['name', 'type']
    schema = csv.DictReader(f, headers)

    for col_def in list(schema)[1:]:# get rid of header line
        sql_parts.append('{} {}'.format(
            col_def['name'].strip(),
            col_def['type'].strip()))

    sql = 'create table settings(' + ', '.join(sql_parts) + ');'
    print(sql)

# or using reader instead of DictReader

with open('table_schema.csv', 'rt', encoding='utf-8') as f:
    sql_parts = []
    columns = 2
    schema = csv.reader(f)

    for row in list(schema)[1:]: # get rid of header line
        if row != []:
            sql_parts.append('{} {}'.format(row[0].strip(), row[1].strip()))

    sql = 'create table settings(' + ', '.join(sql_parts) + ');'
    print(sql)

两者都会输出

create table settings(Setting text, Value integer);