How do I connect to MySQL without using a password? (PyMySQL) - python

Here's the relevant part of my code:
try:
if self.pass_entry.get():
self.connection = pymysql.connect(
host=self.host_entry.get(),
user=self.user_entry.get(),
password=self.pass_entry.get(),
db=self.db_entry.get(),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)
else:
self.connection = pymysql.connect(
host=self.host_entry.get(),
user=self.user_entry.get(),
db=self.db_entry.get(),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)
except Exception as e:
self.console.insert(tk.END, "Error: {err}\n".format(err=str(e)))
Here's the error:
Connecting to 127.0.0.1...
Error: (1045, "Access denied for user 'root'#'localhost' (using password: YES)")
There's no password on "root" here, and PyMySQL is supposing that it has one. How can I connect without using a password? (I've tried to omit the password option when the password field / string is empty, but PyMySQL doesn't take it into account).

When there is no password for the database you need to pass "" to the function as password.
Try this in your else:
else:
self.connection = pymysql.connect(
host=self.host_entry.get(),
user=self.user_entry.get(),
password="",
db=self.db_entry.get(),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)

I had the same problem while using mysql.connector library.
Got around it by simply creating a new connection-user in addition to root.
After googling for a while it seemed like the access to root could be the problem, but I dropped looking further into it after I found the mentioned solution.
The user has the same settings in MySQL as root#localhost.
def mySQLcnx(someVariable):
dbCnx = mysql.connector.connect(host="localhost", user="pythonCnx", database="someDatabase")
dbCnxCursor = dbCnx.cursor()
dbCnxCursor.execute(someStatement)
DbQueryResults = dbCnxCursor.fetchall()

Related

trying to run this command to create a database with mysql but i get a "SQL Syntax error"

This is the error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database' at line 1
Here is the code that I use to create the database:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "password12",
)
my_cursor = mydb.cursor()
my_cursor.execute("CREATE DATABASE database")
my_cursor.execute("SHOW DATABASES")
for db in my_cursor:
print(db)
I tried using a different name for the database, but I still got the same error.
You have an extraneous comma after your password parameter. Change your mydb connection string to the following:
import mysql.connector
mydb = mysql.connector.connect(
host = 'localhost',
user = 'root',
password = 'password12'
)
my_cursor = mydb.cursor()
my_cursor.execute("CREATE DATABASE database")
my_cursor.execute("SHOW DATABASES")
for db in my_cursor:
print(db)
You should use the word password over passwd. Even though they're synonymous, according to the MySQL documentation here: Connector/Python Connection Arguments
An asterisk (*) following an argument indicates a synonymous argument
name, available only for compatibility with other Python MySQL
drivers. Oracle recommends not to use these alternative names.
Argument Name
Default
Description
user (username*)
The user name used to authenticate with the MySQL server.
password (passwd*)
The password to authenticate the user with the MySQL server.
password1, password2, and password3
For Multi-Factor Authentication (MFA); password1 is an alias for password. Added in 8.0.28.
database (db*)
The database name to use when connecting with the MySQL server.
host
127.0.0.1
The host name or IP address of the MySQL server.
Also, as mentioned in the comments above, you should not use the word database as your actual database name. I understand you may be doing it as an example, but its worth noting that it is a Reserved Keyword.

Getting error local variable XXXX referenced before assignment in Python 3.8

I am developing a web app using Angular 9 for frontend and Flask in python 3.8 for backend, everything was going well till i tried to connect the backend with the data base, where the code apparently its ok, flask start running succesfully but when i tried to use my endpoint for authentication, flask throws the error:
**local variable 'conn' referenced before assignment**
i have been checking some forums and so on but i dont understand what is going on. Thanks in advance for your help.
import pymysql
database_name = "dbx80"
database_user = "user_auth"
database_password = "Jan2019#"
def conection_database(db):
try:
conn = (pymysql.connect(
unix_socket="/cloudsql/servicisEX:us-central1:dbx43",
port = 3306,
user = database_user,
password = database_password,
database = database_name,
charset="utf8"
))
print(f"Connection {database_name} Succesful")
except Exception as e:
print(f"Error connecting to {database_name}")
return conn
Converting comment to an answer.
return conn is called no matter the result of the try except block.
If you put the return statement inside the try block, the error will not occur.
Example:
import pymysql
database_name = "dbx80"
database_user = "user_auth"
database_password = "Jan2019#"
def conection_database(db):
try:
conn = (pymysql.connect(
unix_socket="/cloudsql/servicisEX:us-central1:dbx43",
port = 3306,
user = database_user,
password = database_password,
database = database_name,
charset="utf8"
))
print(f"Connection {database_name} Succesful")
return conn
except Exception as e:
print(f"Error connecting to {database_name}")

Connect to MySQL database using python

So I am having a super hard time connecting to a local database using the python mysql.connector module.
So I am trying to connect using the highlighted connection. I use the password abcdefghijkl to log into the SQL environment. I am trying to connect to a database named flight_school.
My python script looks like so.
import mysql.connector
mydb = mysql.connector.connect("localhost", "root", "abcdefghijkl", "flight_school")
print(mydb.is_connected())
This above code in the arguments in the following order i.e.
hostname = localhost,
user = 'root',
password = 'abcdefghijkl', and
database name = 'flight_school'.
It's just not working. I get the following error.
I would really appreciate some advice, please.
Please read always the official documentation
Your cooenction stirng has to have this form(if you do it this way=
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="testpaaword",
database="testdb"
)
Check out SQL-Alchemy module, works wonders from my experience.
Please read always the official documentation: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
import mysql.connector
from mysql.connector import errorcode, MySQLConnection
try:
db_connection = MySQLConnection(user='root', password='', port='3306', database='your_database')
print("Database connection made!")
except mysql.connector.Error as error:
if error.errno == errorcode.ER_BAD_DB_ERROR:
print("Database doesn't exist")
elif error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("User name or password is wrong")
else:
print(error)
else:
db_connection.close()
cursor = db_connection.cursor()
sql = ("commands")
cursor.execute(sql)

Python script unable to connect to MySQL db with no password

I am having a weird issue with my python script. My script has to connect to MySQL DB. This is the code:
try:
conn = MySQLdb.connect( user='root', host = 'localhost')
cursor = conn.cursor()
databases = cursor.fetchall()
cursor.close()
except Exception as e:
print e
when I run this script I have and error like:
(1045, "Access denied for user 'root'#'localhost' (using password: NO")
in the other hand, I can connect to MySQL just by entering MySQL (without password).
Why am I having this error with my python script when there is no password to root user?
Provide empty password
try this
conn = MySQLdb.connect( user='root', host = 'localhost', passwd='')
This should be the syntax. You should have the MySql connector for Python
import mysql.connector
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='database_name')
cnx.close()
try this (inside the bloc try except)
import mysql.connector
conn = mysql.connector.connect(user='root', password='',host='localhost',
database='your_database_name')
conn.close()

Can't connect to mysql using python's mysql.connector

I'm using a Mac (OS 10.10.5), PyCharm, Python 3.5 and MySQL. MySQL has been working with PHP on the same machine. I'm trying to connect to it using Python and getting the error message:
enter code here2003: Can't connect to MySQL server on 'localhost::3306' (8 nodename nor servname provided, or not known)
Can someone list the diagnostic steps so I can correct the problem? Thanks, Doug
Below is the connection code:
import mysql.connector
from mysql.connector import errorcode
try:
cnn = mysql.connector.connect(
host="localhost:", # your host, usually localhost
user="root", # your username
password="root", # your password
database="bb_cards") # name of the data base
print("It Works!!")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with username or Password")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("Database Does not exist")
else:
print(e)
You have a colon where there shouldn't be one:
host="localhost:" # remove the : -> host="localhost"
127.0.0.1::3306 is not the same as 127.0.0.1:3306
There are somethings I make out from your code.
we can provide host="localhost" no semicolons. or we can provide a host/server value like 'host':'127.0.0.1:<port name>'
Check your port again to connect the database
We should always close the connection viz. cnn.close() when our task is complete.

Categories

Resources