【问题标题】:How to create SQL query with each column name and its data type如何使用每个列名及其数据类型创建 SQL 查询
【发布时间】:2017-10-19 17:50:25
【问题描述】:

我有一个 CSV 文件,其中包含 2 列:数据库的列名及其数据类型。我希望编写一个 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)

【问题讨论】:

  • 可以告诉我们您面临什么问题,您还需要显示 CSV 的内容以了解您实际尝试过的内容

标签: python mysql


【解决方案1】:

如果您的 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);

【讨论】:

    【解决方案2】:

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

    您可以使用它生成您的 SQL 查询/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 列表并应用此方法。

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 2016-04-14
      • 1970-01-01
      • 2018-06-20
      • 2020-07-19
      • 1970-01-01
      • 2013-04-02
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多