How to change the authentication configuration of mysql connector to python? - mysql

I was trying to connect MySQL with python via the following code.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="qwerty",
auth_plugin="mysql_native_password"
)
print(mydb)
It gave me the following error:-
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
My connector version is:-
C:\Users\samar>pip install mysql-connector-python
Requirement already satisfied: mysql-connector-python in c:\users\samar\anaconda3\lib\site-packages (8.0.21)

import pymysql
host="localhost"
user="root"
passwd="qwerty"
db="<give db name"
def dbConnectivity(host,user, passwd, db):
try:
db = pymysql.connect(host=host,
user=user,
passwd=passwd,
db=db)
cursor = db.cursor()
print("Great !!! Connected to MySQL Db")
return cursor
except pymysql.Error as e:
print("Sorry !! The error in connecting is:" + str(e))
return str(e)
dbConnectivity(host,user,passwd,db)

Related

ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package v2021

I'm trying a simple database connection.
"""
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='options',
user='root',
password='xxxxx')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
"""
This works - once - if I uninstall and reinstall MySQL. When I try it a second time if fails to the above Traceback. When it works I've tried a simple read of some of the data. This also works only once per reinstall.
"""
import mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='options',
user='root',
password=xxxxxx)
sql_select_Query = "SELECT command” (my SELECT command is lengthy so I’ve omitted it)
cursor = connection.cursor()
cursor.execute(sql_select_Query)
# get all records
records = cursor.fetchall()
print("Total number of rows in table: ", cursor.rowcount)
print("\nPrinting each row")
for row in records:
print("col1 = ", row[0], )
print("col2 = ", row[1])
print("col3 = ", row[2])
print("col4= ", row[3], "\n")
except mysql.connector.Error as e:
print("Error reading data from MySQL table", e)
finally:
if connection.is_connected():
connection.close()
cursor.close()
print("MySQL connection is closed")
"""
I've done the MySQL installation of the server, workbench, and connector (3x).
I'm using Windows 10 Home with the latest Anaconda release.
Python 3.8.11 (default, Aug 6 2021, 09:57:55) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
I’ve uninstalled ALL mysql entries in the pip list and reinstalled them (multiple times).
I have no issues accessing the database from MySQL Workbench.
(base) PS C:\Users\WARNE> pip list
Package Version
mysql 0.0.3
mysql-connector-python 8.0.26
mysqlclient 2.0.3
(base) PS C:\Users\WARNE> conda install -c anaconda mysql-connector-python
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
…this continued to fail
I've tried about every solution in all of the related questions without any luck. Any help/suggestions would be appreciated.
I finally went back to basics and re-installed, went to very simple code, etc. and this started working. This seems to be a weakness in python-MySQL interworking. This was frustrating.

Why do I get TCP/IP error when trying to create DB in my Lambda?

So I'm trying to deploy my Django project using lambda, with zappa. I'm using MySQL for DB engine. Now after doing some research, I realized that I needed to create a custom Django command to create DB, since I'm using MySQL. So I created crate_db command, zappa updated, then ran zappa manage dev create_db. Then I got this error: 2004 (HY000): Can't create TCP/IP socket (97)
below is my create_db.py file, for your information.
import sys
import logging
import mysql.connector
import os
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
rds_host = os.environ.get("MY HOST")
db_name = os.environ.get("")
user_name = os.environ.get("MY USERNAME")
password = os.environ.get("MY PASSWORD")
port = os.environ.get("3306")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class Command(BaseCommand):
help = 'Creates the initial database'
def handle(self, *args, **options):
print('Starting db creation')
try:
db = mysql.connector.connect(host=rds_host, user=user_name,
password=password, db="mysql", connect_timeout=10)
c = db.cursor()
print("connected to db server")
c.execute("""CREATE DATABASE bookcake_db;""")
c.execute("""GRANT ALL ON bookcake_db.* TO 'ryan'#'%'""")
c.close()
print("closed db connection")
except mysql.connector.Error as err:
logger.error("Something went wrong: {}".format(err))
sys.exit()
Any ideas? Thanks.

Error when connecting to MySQL database using mysql.connector

I am trying to connect to a MySQL database using mysql.connector:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
password="password",
database="database"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM table")
myresult = mycursor.fetchone()
print(myresult)
I get this error message:
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on'localhost:3306'(10061 No connection could be made because the target machine actively refused it)
Does this mean that there something wrong with the database credentials?

cursor() and connection() methods are not working while trying to connect MySQL via Python(using Pycharm)

I am trying to connect MySQL database via python. I initially installed mysql-connector which did not work. later I installed mysql-connector-python and connection was successful. But when I tried to use cursor(), getting error:
Code:
import _mysql_connector
mydb = _mysql_connector.MySQL().connect(host="localhost", user="root", password="1234")
mycursor = mydb.cursor()
mycursor.execute("show databases")
Error: AttributeError: 'NoneType' object has no attribute 'cursor'
**
Solved(used alternate module: MySQLdb)
:**
--- mysql.connector did not work for me, I used an alternate module MySQLdb which I installed using pip3 install mysqlclient.
code:
import MySQLdb
mydb = MySQLdb.connect(user="root", host="localhost", password="1234", database="mydatabase")
cursor = mydb.cursor()
cursor.execute("select * from tableName")
for i in cursor:
print(i)
cursor.close()
mydb.close()
You're trying to connect using C Extension Module. Here is basic Connector example:
import mysql.connector
mydb = mysql.connector.connect(user='root', password='1234', host='localhost', database='myDatabase')
cursor = mydb.cursor()
cursor.execute('show databases')
/*
.
.
.
*/
cursor.close()
mydb.close()

Connecting to MySQL via Python and I have contradictory results

I am trying to connect to a MySQL database hosted on Python Anywhere. In the below example connection.get_server_info() returns a result however connection.is_connected() returns False and I am unsure why.
Here is my code:
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USERNAME', ssh_password='PASSWORD',
remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='USERNAME', password='DB_PASSWORD',
host='127.0.0.1', port=tunnel.local_bind_port,
database='USERNAME$default',
)
db_info = connection.get_server_info()
if connection.is_connected():
print('Connected to MySQL DB...version on ', db_info)
else:
print('Failed to connect.')
print(db_info)
connection.close()
I have a paid account on Python Anywhere so SSH tunneling should be possible
It's because you're trying to access the SSH tunnel after it has been closed; the tunnel is closed when you exit the with block, so anything that uses the connection needs to be indented so that it is contained within it. Your code above look like this:
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USERNAME', ssh_password='PASSWORD',
remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='USERNAME', password='DB_PASSWORD',
host='127.0.0.1', port=tunnel.local_bind_port,
database='USERNAME$default',
)
db_info = connection.get_server_info()
if connection.is_connected():
print('Connected to MySQL DB...version on ', db_info)
else:
print('Failed to connect.')
print(db_info)
connection.close()