Error when connecting to MySQL database using mysql.connector - mysql

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?

Related

How to import .DB file by connecting MYSQL in R

I have a .db file like "sakila"
library(RMySQL)
library(DBI)
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '123456', dbname = 'sakila',host = 'localhost')
dbListTables(mysqlconnection)
It reports the error:
Error in .local(drv, ...) :
Failed to connect to database: Error: Unknown database 'sakila.db'
How do I fix it?
I hope to import the .db file in Mysql by using R.

Pythonanywhere giving MySQL connection error even without time delay

I am trying to connect to my pythonanywhere DB from a local python file, using the following code.
import MySQLdb, sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
queryAdd = ("INSERT INTO `****$geo***`.O***"
"(name, address) "
"VALUES (%s, %s)")
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='*******', ssh_password='*******',
remote_bind_address=('*****.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='******',
passwd='********',
host='127.0.0.1', port=tunnel.local_bind_port,
db='****$geo******',
)
cursor = connection.cursor()
for row in dl:
tup=(row['name'],row['address'])
cursor.execute(queryAdd, tup)
connection.commit()
However, as soon as the code is run, I get the following error:
MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
There is no delay between creating the connection and running the query. What am I doing wrong?
You need to do everything inside your with block as the tunnel is gone when you go outside of the context.

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.

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()

MySQL Operational Error

I am trying to upload data into a MySQL database, but I am having trouble doing so. The error I receive when I try to run my code is 2003, Can't connect to MySQL server on 'db_host' ([Errno 11001] getaddrinfo failed). Does anyone know what this error means or how to fix it? I have included my code below.
import pymysql
import time
import good_morning as gm
DB_HOST = 'db_host'
DB_USER = 'db_user'
DB_PASS = 'db_pass'
DB_NAME = 'db_name'
conn = pymysql.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)
kr = gm.KeyRatiosDownloader()
fd = gm.FinancialsDownloader()
kr_frames = kr.download('AAPL', conn)
fd_frames = fd.FinancialsDownloader()