从python列表创建MySql表
16lz
2021-01-22
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
更多相关文章
- mysql如何判断一个字符串是否包含另外一个字符串?
- mySQL:按给定的ID字符串排序ID? (为分层数据构建面包屑)
- 用PHP比较PHP中的字符串
- 如何用C++向MYSQL插入UNICODE字符串?
- MySQL 示例数据库sakila
- 由于底层异常,无法加载连接类:'java.lang.NumberFormatException:对
- MySQL官网示例数据库emploees分析使用
- 如何在mysql数据库中找到类似的二进制字符串?
- SQL从结果数据库中选择subCode及其得分,并将其输出为一个字符串