here i want to name the table name according to user desire but i can’t please help
** I HAVE INCLUDED THIS CODES FOR CONNECTING PYTHON TO DATABASE **
import mysql.connector from mysql.connector.abstracts import MySQLCursorAbstract mydb= mysql.connector.connect(host="localhost",user="root",passwd="",database="python") mycursor = mydb.cursor()`
print("do you want to build table") g=input() if(g=='yes'or g=='YES'): print("please enter table name") enter code here k=input() mycursor.execute("create table " )
Advertisement
Answer
The syntax for creating a table in mySql looks like this:
CREATE TABLE my_table_name (my_first_column INT);
This will create the table named “my_table_name” with one column named “my_first_column” of type integer.
To implement this in you can use string formatting
mycursor.execute("CREATE TABLE {} (my_first_column INT)".format(k))
or if you’re using >Python3.7 you can use handy f-strings
mycursor.execute(f"CREATE TABLE {k} (my_first_column INT)")
You should also consider sanitzing the users input k
to prohibit an SQL-injection.