0

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?

2
  • Where is the list of strings coming from? User entered data? Commented Jan 11, 2020 at 4:38
  • I am scraping a website and getting the strings from the HTML, and then adding them to the list Commented Jan 11, 2020 at 4:47

1 Answer 1

1

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))
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.