2

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

2
  • What is the problem? It should be straight forward writing a related SQL string from your data?! What have you tried so far? Is this homework? Commented May 6, 2011 at 16:49
  • 3
    @Sentinel Nop. Not homewok. Sorry but the rest of your comment isn't worth a serious answer. Commented May 6, 2011 at 18:15

1 Answer 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           
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.