Home > Software design >  i cant use python input to create mysql database
i cant use python input to create mysql database

Time:01-10

I want to take input from user of creating a mysql database I cant use python input to create mysql databasewhat i tryed

Getting this error please help the error

CodePudding user response:

execute() method parameters must be provided as a tuple, dict or a list :

cursor.execute(cdb, (dbname,))

And I think you can execute your query directly like :

%-formatting

cdb = 'CREATE DATABASE %s' % dbname 
cursor.execute(cdb)

F-strings

cdb = f'CREATE DATABASE {dbname}'
cursor.execute(cdb)

str.format()

cdb = 'CREATE DATABASE {}'.format(dbname) 
cursor.execute(cdb)

Consider using f-strings when dealing with string that contains variables.

cdb = f'CREATE DATABASE {dbname}'

CodePudding user response:

Try this way, this works correctly.

try:import mysql.connector as con
except ImportError:print("⚠ Install correctly mysql.connector")

db = con.connect(host="localhost",user="<username>",passwd="<password>")
cursor = db.cursor()

dbname = input("Enter ddbb name to create: ")
cdb = f"CREATE DATABASE {dbname}"

try:cursor.execute(cdb)
except NameError:print(NameError)
  • Related