Python scripts and MySQL - python

Good day!
I have a question annoying me. I setup Apache server/MySQL/PhpMyAdmin on my PC. And i'd like to write some scrips on python3 to work with database. I setup my db on localhost. But now the local network has another one computer.
I wish my friend could access the database through my ip. like (http :// 192.168.xx.xx / pma).
and now it works!
My friend loves python too. And there is a problem: When he's run script, python waits 30 sec and:
"Can't connect to MySQL server on %r (%s)" % (self.host, e))
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '192.168.
xx.xx' ([WinError 10060] A connection attempt failed because the connected part
y did not properly respond after a period of time, or established connection fai
led because connected host has failed to respond)")
There peace of code to connect:
import pymysql
con = pymysql.connect(host='192.168.xx.xx', user='root', passwd='xxx', db='test')
cur = con.cursor()
print(con)
Help my friend to work with my database!
Thanks you!

You have to give remote access to your mysql database.
Then give grant to your user.
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;

Related

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.

how to use Python3.3 access online MySQL Database

I am new to python and network programming.
Recently I am having trouble accessing my online database.
The problem is that I want to write a code and execute it on my computer to acces my online data base, and the only thing I want to do is to access the informaion in my database and do some change.
The first question is that I don't know what to use as parameters.
here is what show up on my online database, which I can access using internet browser:
173.201.136.195
Server version: 5.0.96-log
Server: 173.201.136.195 via TCP/IP
User: user123123#72.167.233.37
MySQL charset: UTF-8 Unicode (utf8)
I don't understand which ip should I use when i connect to it, '173.201.136.195' or '173.201.136.195' and which username should I use. 'user123123' or 'user123123#72.167.233.37'
This is the code I use:
conn = pymysql.connect(host='173.201.136.195',user='user123123',passwd="123123123",db='TestData')
phthon shell shows that:
File "F:\Program Files\Python33\lib\pymysql\connections.py", line 819, in _connect 2003, "Can't connect to MySQL server on %r (%s)" % (self.host, e))
pymysql.err.OperationalError: (2003, 'Can\'t connect to MySQL server on \'173.201.136.195\' ((1045, "Access denied for user \'user123123\'#\'142.151.201.116\' (using password: YES)"))')
What on earth is 142.151.201.116 ?
the error means that access to the server 173.201.136.195 is denied to the user user123123 at ip 142.151.201.116. When you give access to a user on mysql database you specify the ip or wildcads for multiple ips. So access to the database for user is per ip.
example:
GRANT ALL PRIVILEGES ON *.* TO 'username'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
will give access to username on all hosts. but this:
GRANT ALL PRIVILEGES ON *.* TO 'username'#'10.20.30.40' IDENTIFIED BY 'password' WITH GRANT OPTION;
will give access to username at ip 10.20.30.40
this information is on mysql.user table

How to connect to remote mysql server in python

Hi i have a requirement where i need to connect to remote mysql server. My application shall be running on local machine and my mysql will be running on remote server.I have tried the following code:
DB = 'gts'
DB_HOST = 'ps95074.dreamhost.com'
DB_USER = 'root'
DB_PASSWORD = 'dbadminpassword'
conn = MySQLdb.Connection(db=DB, host=DB_HOST, user=DB_USER,passwd=DB_PASSWORD)
cursor = conn.cursor()
But i am getting the following error
OperationalError: (2005, "Unknown MySQL server host 'ps95074.dreamhost.com' (1)")
Instead if i use
DB_HOST='localhost'
Everything works fine. How can same be possible with remote host.Any help shall be appreciated.
Check your firewall. That server is online and available from any machines:
> mysql -h ps95074.dreamhost.com
ERROR 1045 (28000): Access denied for user 'myuser'#'myhost' (using password: NO)
However, even if you can connect chances are good that your database user only allows local connections.
Update: I just tried it again and now it also fails using the commandline client. So clearly something is wrong with your server.

python mysql connection problem

This code works fine:
import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
but if I give my IP address
db = MySQLdb.connect("192.168.*.*", "root", "","bullsorbit")
it will give this error
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'ip address' (111)")
Code 2003 is a standard MySQL client error:
Error: 2003 (CR_CONN_HOST_ERROR) Message: Can't connect to MySQL server on '%s' (%d)
I'd guess that your user is not allowed to connect to the MySQL server using an iP-address. What happens if you try a connection usign the MySQL commandline client?
$ mysql --host=192.168.1.1 -u root bullsorbit
with localhost you connect via loopback-interface.
with ip-addr you connect - as you connect from extern.
if your server allows only the local (loopback) connection
your ip-addr connection fails. (security!)
look at your mysql config, maybe only local-connections are allowed.
is the skip-networking switch off (in the mysql-conf) ?
#skip-networking
For the 2003 error, another possibility is that too many connections are being attempted in too short of time. I noticed this same behavior when I had 127.0.0.1 as my connect string. First I replaced it with localhost which got me further but still the same 2003 error. Then I saw that if I scaled back the number of calls the error disappeared completely.
Instead of:
db = MySQLdb.connect("192.168..", "root", "","bullsorbit")
try:
db = MySQLdb.connect(user="root", host="192.168..", db="bullsorbit")
Password will default to empty string and try the usual identity methods. Host will also default to localhost on default port.

Categories

Resources