Reputation: 413
I have a list of strings, which I want to use as column names. I am using pymysql
.
I am aware of the other similar question, but I am not using the package mentioned there.
How can I do this?
Upvotes: 0
Views: 60
Reputation: 2088
Off the top of my head I think using jinja might work. You could create a template and pass in the values as variables, render the template and use the resulting string as your statement. It would also be possible to change the example below so that you could also pass in the data types. Something else to consider is sanitizing the strings in the list to make sure they are safe since they are coming from the internet.
from jinja2 import Template
a= ['abc', 'efg', 'hij', 'klm']
table_syntax = """
CREATE TABLE `{{ table_name }}` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
{% for column in columns %}
`{{ column }}` varchar(255) NOT NULL {{ "," if not loop.last }}
{% endfor %}
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1;
"""
template = Template(table_syntax)
print(template.render(table_name="example", columns=a))
Upvotes: 1