I want to connect with MySQL through Python, although I am successful in connecting using directly writing the credentials like user name, passwd, etc, but I want to make it a little dynamic. So I tried:
import mysql.connector
import pandas as pd
def connection():
host=input('Enter host')
user=input('Enter User Name')
passwd=int(input('passwd'))
database=input('database')
mydb= mysql.connector.connect(host="host", user="user", passwd="passwd", database="database")
return mydb
connection()
However, it gives error in the end:
InterfaceError: 2003: Can't connect to MySQL server on 'host:3306' (11001 getaddrinfo failed)
Please help me out. And if you have better solution while bringing some dynamic user input credential, I will be really grateful. Thank you.
-
1Have you tried this? mydb= mysql.connector.connect(host=host, user=user, passwd=passwd, database=database)vishal– vishal2021年07月07日 17:56:57 +00:00Commented Jul 7, 2021 at 17:56
2 Answers 2
You are passing stirng like "host" to the database and not the variables
So remove the double quotes like
import mysql.connector
import pandas as pd
def connection():
host=input('Enter host')
user=input('Enter User Name')
passwd=int(input('passwd'))
database=input('database')
mydb= mysql.connector.connect(host=host, user=user, passwd=passwd, database=database)
return mydb
connection()
Comments
In the connect method of the mysql.connector you are hardcoding the values when you pass them as strings.
Use mysql.connector.connect(host=host, user=user, passwd=passwd, database=database) instead.
You're also parsing the password to a int, I don't think mysql will like that, just use it as a string.