Creating MySql Table from a python list
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
精彩评论