I have a large list of strings. I need to create a MySQL table where each string in the list is a name of a column (all columns are integers). (I'm on python with sqlalchemy).

我有一个很大的字符串列表。我需要创建一个MySQL表,其中列表中的每个字符串都是一个列的名称(所有列都是整数)。 (我正在用sqlalchemy进行python)。

I looked at examples and it looks like I need to explicitly write each column in schema.Table, which is not so practical for a large list.

我查看了示例,看起来我需要在schema.Table中显式编写每一列,这对于大型列表来说并不实用。

Is it possible?

可能吗?

Thanks

1 个解决方案

#1


2

You could use tuple unpacking here.

你可以在这里使用元组解包。

>>> column_names = ['col1', 'col2', 'col3']
>>> columns = (Column(name, Integer) for name in column_names)  
>>> table = Table('table_name', metadata, *columns) # unpacks Column instances

And here's an extended example of how you could use this to programmatically create the column names from a list of strings:

这是一个扩展示例,说明如何使用它以编程方式从字符串列表中创建列名:

>>> column_names = ['col1', 'col2', 'col3']
>>> columns = (Column(name, Integer) for name in column_names)
>>> table = Table('data', metadata, Column('id', Integer, primary_key=True), *columns)
>>> class Data(object):
...:     def __init__(self, *args):
...:         for name, arg in zip(column_names, args):
...:             setattr(self, name, arg)
...:             
...:
>>> mapper(Data, table)
<<< <Mapper at 0x1026e9910; Data>
>>> data = Data(1, 2, 3)
>>> [x for x in dir(data) if x.startswith('col')] # see if all of our columns are there
<<< ['col1', 'col2', 'col3'] 
>>> data.col3 # great!
<<< 3           

更多相关文章

  1. mysql如何判断一个字符串是否包含另外一个字符串?
  2. mySQL:按给定的ID字符串排序ID? (为分层数据构建面包屑)
  3. 用PHP比较PHP中的字符串
  4. 如何用C++向MYSQL插入UNICODE字符串?
  5. MySQL 示例数据库sakila
  6. 由于底层异常,无法加载连接类:'java.lang.NumberFormatException:对
  7. MySQL官网示例数据库emploees分析使用
  8. 如何在mysql数据库中找到类似的二进制字符串?
  9. SQL从结果数据库中选择subCode及其得分,并将其输出为一个字符串

随机推荐

  1. go语言中make和new的区别是什么?
  2. 编程语言go是什么
  3. go语言中数组和切片的区别是什么?
  4. go语言适合做哪些开发
  5. win7 go语言如何安装
  6. 关于Golang连接池的几种实现案例
  7. go语言实现string转float的方法
  8. 详解Go 中方法与函数的区别
  9. go是开源语言吗?
  10. 解析Go中的多态 -无需interfaces