Accessing a SQL database from remote PC - python

When I started hosting my website, I received a phpMyAdmin thing where I could manage the databases for the website. How can I access those databases from my remote PC?
I tried connecting to one using Python but I keep getting the error (10061 No connection could be made because the target machine actively refused it) and I need help because I don't know how to solve it.
Here is the code I wrote:
import mysql.connector
try:
mydb = mysql.connector.connect(
host='localhost',
user='someuser',
password='somepass',
database='database'
)
except Exception as e:
print(type(e))
print(e)

You should not be using localhost if you are connecting to a remote database which is on another server machine. Instead use the database server IP address:
import mysql.connector
try:
mydb = mysql.connector.connect(
host='11.162.174.78',
port='3306',
user='user_id',
password='user_password',
database='name_of_database'
)
except Exception as e:
print(type(e))
print(e)
Having said this, in your question above you mentioned 'managed the databases for the website', to which I would suggest that you use a proper database management tool such as MySQL Workbench or HeidiSQL.

Related

Connect to a database located on phpmyadmin from python

I'm looking to connect to a database via python.
The database is on phpmyadmin.
I read the section "variable" on phpmyadmin and I saw that the hostname is "atexo-sourcing-prod-01.local-trust.com".
Unfortunately, when I try to connect with this python code and with the same login and password that I use to connect to phpmyadmnin:
try:
conn = mariadb.connect(
user="mylogin",
password="my_password",
host="atexo-sourcing-prod-01.local-trust.com",
port=3306,
database="atexo_prod_sourcing_db")
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
I have an error, saying
Can't connect to server on 'atexo-sourcing-prod-01.local-trust.com'
(10061)
(I think it's not a problem of hostname, because when I put a random name, I have an other error).
Any idea to fix this?

MySQL Connector/Python Error "Lost connection to MySQL server / Connection reset by peer"

I am new to Python and mySQL and I am trying to get the following Python script running as a CGI on an hosted webserver:
#!/usr/bin/python3
import cgi
import sys
sys.path.append("PATH TO SIDE PACKAGES DUE TO MISSING ROOT ACCESS")
import mysql.connector
from mysql.connector import Error
print('Content-type: text/html') # the mime-type header.
print() # header must be separated from body by 1 empty line.
try:
connection_config_dict = {
'user': 'MY_USER',
'password': 'MY_PASSWORD',
'host': 'rdbms.strato.de',
'database': 'MY_DATABASE',
}
connection = mysql.connector.connect(**connection_config_dict)
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("Your 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")
Unfortunately, this results in the following error message:
Error while connecting to MySQL 2055: Lost connection to MySQL server at 'rdbms.strato.de:3306',
system error: 104 Connection reset by peer
I looked up older threads with the error message and while I could find both separately, I did not find them in this combo, therefore I hope there might be someone having an idea for a solution before I deal with the horrible customer service of my provider again. To me as a newbie it seems like the server declines the connection, even though I am coming from inside the network (running as a CGI on the server).
Some more information about the environment: The Python version is 3.8.1, mySQL server version 5.7, mysql_connector_python version 8.0.23. Since it is a hosted webserver I do not have root access, therefore I installed additional modules with pip --user via ssh and added the path to the script which works fine with other modules like requests. I am also certain that the mySQL login data is correct, since it works flawlessly with a PHP script.
Thanks in advance for helping out!

PyMySQL using localhost vs socket incoherant behaviour

I am using PyMySQL to connect to a database running on localhost. I can access the database just fine using the username/password combiunation in both the command line and adminer so the database does not appear to be the probem here.
My code is as follow. However, when using the host="127.0.0.1" options, I get an OperationalError and an Errno 111. Using the same code, but connecting via the socket Mariadb runs on is fine.
import pymysql.cursors
from pprint import pprint
# This causes an OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
# connection = pymysql.connect(
# host="127.0.0.1",
# port=3306,
# user="root",
# password="S3kr37",
# db="my_test",
# )
# This works.
connection = pymysql.connect(
user="root",
password="S3kr37",
db="my_test",
unix_socket="/var/lib/mysql/mysql.sock"
)
try:
with connection.cursor() as cursor:
sql = "select * from MySuperTable"
cursor.execute(sql)
results = cursor.fetchall()
pprint(results)
finally:
connection.close()
What am I doing wrong?
PS: Note that this question has the same problem but the solution offered is the socket. That is no good enough: I want to know why I cannot use the hostname as the documentation suggests.
Errorcode 2003 (CR_CONN_HOST_ERROR) is returned by the client library, in case the client wasn't able to establish a tcp connection to the server.
First you should check, if you can connect via telnet or mysql command line client to your server.
If not, check the server configuration file:
does the server run on port 3306?
is IPv4 disabled?
is skip-networking enabled?
is bind-address activated (with another IP?

Connecting to MYSQL AWS-RDS using SQLAlchemy in Pycharm/ with Python

Click to see RDS settings
Im trying to connect to a MYSQL server on Amazons Web Service, specifically the RDS- using SQLAlchemy in python (Pycharm).
I've already installed drivers for pymysql to include in the connection string for the engine (engine = create_engine("mysql+pymysql://...).
I've tried setting the CIDR security group inbound and outbound rules to allow any IP.
I can connect to the AWS-RDS just fine from MYSQL Workbench suing the Endpoint, Port and credentials.
I was able to connect to a local instance of MYSQL using SQLAlchemy and create_engine(...) without any issues too.
I've tried including and excluding the port from the URL.
try: # exception handling for database creation/ existence
engine = create_engine(link_to_db, pool_pre_ping=True, pool_recycle=3600) # Access the DB Engine
connection = engine.connect()
print("Database conn 1 successful")
except Exception as e:
logging.exception(e)
print("error connecting to db")
where link_to_db is "mysql+pymysql://{RDS USERNAME}:{RDS PASSWORD}#
{RDS ENDPOINT}:3306/{DATABASE NAME}"
The expected result is
"Database conn 1 successful"
printed to the output.
Errors :
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '{RDS URL}' ([Errno 11001] getaddrinfo failed)")
(Background on this error at: http://sqlalche.me/e/e3q8)
Kindly check the below things.
1) Check your rds is publicly accessible to YES. if its in private subnet check connectivity between your source(office/home/etc) to destination(RDS).
2) open 3306 in the security group.
3) check master user credentials.
# telnet {rds end-point} 3306
I found that it was as simple as changing from a multiline string """ {link} """ to single quotes '{link}'.

MySQL Connector in Python

Trying to connect to my MySQL DB on my VPS. I'm getting the following error, when using the below code;
(I've stripped out my credentials - however I know they work, as I use them for my PHP dev as well.
CODE
import mysql.connector as mysql
from mysql.connector import errorcode
try:
conn = mysql.connect( user= %USER%
,password=%PW%
,host = %HOST%
,database = %DB%
)
except mysql.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
else:
conn.close()
ERROR MESSAGE
2003: Can't connect to MySQL server on '%HOST%:3306' (10060 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)
Connector That I'm using
http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.1-py3.4.msi
Any idea what I'm doing wrong?
Check the GRANT on your MySQL database. It might be that you haven't been GRANTed permission to connect from that host with the given username and password.
The MySQL error number is 2003. I usually find it helpful to do a Google search to see if others have had the problem:
http://dev.mysql.com/doc/refman/5.0/en/access-denied.html
Is there a firewall between the client machine and the database server? I would hope that port 3306 would be blocked by default. If that's true, you'll need to set up a firewall rule to allow access from the client IP to the database IP via port 3306.

Categories

Resources