开发者

Creating MySql Table from a python list

开发者 https://www.devze.com 2023-03-03 17:15 出处:网络
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 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).

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.

开发者_开发知识库

Is it possible?

Thanks


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           
0

精彩评论

暂无评论...
验证码 换一张
取 消