Issue to connect into a mysql database with MySQLdb module (python) - python

I have a database in mysql and I want to connect to it. I am trying to use this module from Python called MySQLdb. I created an user (called abc) and password (abc) for this database (abc) that has one table and it is connecting ok (when I connect by mysql command line).
But when I run my python script there is an error in the connection.
My script is:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","abc","abc","abc")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data
# disconnect from server
db.close()
My error is:
Traceback (most recent call last):
File "./test.py", line 8, in <module>
db = MySQLdb.connect("localhost","abc","abc","abc")
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 193, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1044, "Access denied for user 'abc'#'localhost' to database 'abc'")
What is wrong? My script or something in my mysql?
I changed my localhost to 127.0.0.1 (as suggested in another post, but did not solve my issue.
I also checked my permissions for this mysql user:
SHOW GRANTS;
+------------------------------------------------------------------------------+
| Grants for abc#localhost |
+------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'abc'#'localhost' |
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, CREATE VIEW ON `abc`.* TO 'abc'#'localhost' |
+------------------------------------------------------------------------------+

You might need to restart the mysql daemon for the privileges to take affect. Or use the flush privileges command. https://dev.mysql.com/doc/refman/5.7/en/privilege-changes.html

Related

Using Python to connect to Impala database (thriftpy error)

What I'm trying to do is very basic: connect to an Impala db using Python:
from impala.dbapi import connect
conn = connect(host='impala', port=21050, auth_mechanism='PLAIN')
I'm using Impyla package to do so. I got this error:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/thriftpy/transport/socket.py", line 96, in open
self.sock.connect(addr)
socket.gaierror: [Errno -3] Temporary failure in name resolution
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/alaaeddine/PycharmProjects/test/data_test.py", line 3, in <module>
conn = connect(host='impala', port=21050, auth_mechanism='PLAIN')
File "/usr/local/lib/python3.6/dist-packages/impala/dbapi.py", line 147, in connect
auth_mechanism=auth_mechanism)
File "/usr/local/lib/python3.6/dist-packages/impala/hiveserver2.py", line 758, in connect
transport.open()
File "/usr/local/lib/python3.6/dist-packages/thrift_sasl/__init__.py", line 61, in open
self._trans.open()
File "/usr/local/lib/python3.6/dist-packages/thriftpy/transport/socket.py", line 104, in open
message="Could not connect to %s" % str(addr))
thriftpy.transport.TTransportException: TTransportException(type=1, message="Could not connect to ('impala', 21050)")
Tried also the Ibis package but failed with the same thriftpy related error.
In Windows using Dbeaver, I could connect to the database using the official Cloudera JDBC connector. My questions are:
Should pass my JDBC connector as parameter in my connect code? I have made some search I could not find something pointing at this direction.
Should I try something else than Ibis and Impyla packages? I had experienced a lot of version related issues and dependencies when using them. If yes, what would you recommend as alternatives?
Thanks!
Solved:
I used pyhive package instead of Ibis/Impyla. Here's an example:
#import hive from pyhive
from pyhive import hive
#establish the connection to the db
conn = hive.Connection(host='host_IP_addr', port='conn_port', auth='auth_type', database='my_db')
#prepare the cursor for the queries
cursor = conn.cursor()
#execute a query
cursor.execute("SHOW TABLES")
#navigate and display the results
for table in cursor.fetchall():
print(table)
Your impala domain name must not be resolving. Are you able to do nslookup impala in command prompt? If you're using Docker, you need to have the docker service name in docker-compose as "impala" or have "extra_hosts" option. Or you can always add it to /etc/hosts (Windows/Drivers/etc/hosts) as impala 127.0.0.1
Also try 'NOSASL' instead of PLAIN sometimes that works better with security turned off.
This is the simple method, connecting impala through impala shell using python.
import commands
import re
query1 = "select * from table_name limit 10"
impalad = str('hostname')
port = str('21000')
database = str('database_name')
result_string = 'impala-shell -i "'+ impalad+':'+port +'" -k -B --delimited -q "'+query1+'"'
status, output = commands.getstatusoutput(result_string)
print output
if status == 0:
print output
else:
print "Error encountered while executing HiveQL queries."

Mysql OperationalError 1044, connect to mysql database

f_dbI am trying to connect to mysql database using a python script. My code to do so is the following:
`db = MySQLdb.connect(host="xxx.xx.xx.xx", # your host, usually localhost
port = xxxx,
user="chrathan", # your username
passwd="...", # your password
db="f_db") # name of the data base`
I ve open the database from mysql workbench. However, I am not able to open it from python I am getting the following error:
_mysql_exceptions.OperationalError: (1044, "Access denied for user 'chrathan'#'%' to database 'f_db'"). Basically I am receiving `Traceback (most recent call last):
File "D:\_WORKSPACE\mysql\fashion_db.py", line 7, in <module>
db = 'f_db') mysql_exceptions.OperationalError: (1044, "Access denied for user 'chrathan'#'%' to database 'f_db'")`
enter this command on mysql terminal
$> mysql
GRANT ALL PRIVILEGES ON f_db.* TO 'chrathan'#'%' identified by 'secret'
for add user to database in mysqlworkbench look at this page How to Create a MySQL Database with MySQL Workbench
maybe you should check db name whether is same, the same problem occour on me, finally i found mysqlclient db name is not same as i use in python

Python connecting to mysql

I installed Python 2.7 to try to connect to MySQL online. Basically, MySQL and phpMyAdmin is on a server and I can access it via localhost:8888/phpmyadmin via putty on my windows desktop. I cant seem to connect to it even with the putty on. Any idea? I face the same issue with Python 3.3 using CyMySQL.
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", # your host, usually 127.0.0.1
user="megamonster", # your username
passwd="", # your password
db="extractor") # name of the data base
# you must create a Cursor object. It will let
# you execute all the query you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM abc")
# print all the first cell of all the rows
for row in cur.fetchall() :
print row[0]
Error:
Traceback (most recent call last):
File "C:\Users\Jonathan\Desktop\testSQL.py", line 6, in <module>
db="extractor") # name of the data base
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (10061)")
Update
i added port(3306) and got this.
OperationalError: (2013, "Lost connection to MySQL server at 'waiting for initial communication packet', system error: 0")
Currently looking at
MySQL error: 2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0"
Hmm cant work still...
I used sqlplus it worked
sqlplus User_name/password#Host_ip:Port/Service_Name#$SQLFILENAME
Just specify the SQLFILENAME if you want to utilize a file. Otherwise, you can ignore this parameter and can directly run sql statements
It could be a number of things, but as far as MySQL is concerned, permissions are set independently for localhost and for 127.0.0.1. Make sure you can connect with the exact host and credentials. Possibly related
For example, check this when connected with your PUTTY connection.
mysql> use mysql;
Database changed
mysql> SELECT host,user,select_priv FROM user;
+-------------------------+------+-------------+
| host | user | select_priv |
+-------------------------+------+-------------+
| localhost | root | Y |
| 127.0.0.1 | root | Y |
+-------------------------+------+-------------+
Also check who you are connected as (on PUTTY) and use that same info in the script:
mysql> SELECT USER(),CURRENT_USER();
+----------------+----------------+
| USER() | CURRENT_USER() |
+----------------+----------------+
| root#localhost | root#localhost |
+----------------+----------------+

tornado and postgresql

I'm using demo from facebook's tornado
But I don't want to use MySQL and trying to replace it with PG
So I went ahead and modified like this :
define("port", default=8888, help="run on the given port", type=int)
define("pgsql_host", default="127.0.0.1:5432", help="blog database host")
define("pgsql_database", default="pgdb", help="blog database name")
define("pgsql_user", default="admin", help="blog database user")
define("pgsql_password", default="pgpass", help="blog database password")
and
# Have one global connection to the blog DB across all handlers
self.db = tornado.database.Connection(
host=options.pgsql_host, database=options.pgsql_database,
user=options.pgsql_user, password=options.pgsql_password)
But app just hangs when I run it, how to properly migrate it to PG?
Actually I get error after some time:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/database.py", line 84, in __init__
self.reconnect()
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/database.py", line 101, in reconnect
self._db = MySQLdb.connect(**self._db_args)
File "/usr/lib/pymodules/python2.7/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")
Why is it connecting to MySQL?
Are you sure you can use it with different RDBMS including PostgreSQL?
It uses torndb package which is written to work with MySQL.
So i think that if you want to use it with PostgreSQL you should write your own torndb package for postgresql.
EDIT:
As you can see at Tornado Wiki you have to have postgresql wrapper (momoko or psycopg) there are some links for further study.
EDIT2: Momoko description:
"An asynchronous Psycopg2 wrapper for Tornado."
tornado.database (which will be broken out of Tornado in 3.0) is a lightweight MySQL wrapper. It doesn't support anything other than MySQL.
The good news is, as #sufleR noted, you have some options. You can use pyscopg directly, or you can use momoko, an async wrapper for pyscopg.

python MySQLdb godaddy.com hosting

import MySQLdb
conn = MySQLdb.connect('localhost', 'user', 'pwd', 'sampledb')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.7/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (110)")
How do I connect and what is the issue here? Thank you!
You do not connect to a database on localhost on Go Daddy shared hosting. You will need to locate the correct database host.
Log in to your Account Manager.
Click Web Hosting.
Next to the hosting account you want to use, click Launch.
In the Databases section of the Hosting Control Center, click the MySQL icon.
Click the pencil icon next to the database you would like to get connection strings for.
Your database host name displays in the Host Name field. It will end with "hostedresource.com".
See godaddy's help pages:
http://support.godaddy.com/help/39
import MySQLdb
conn = MySQLdb.connect("host", "user", "password", "database")
host: Get in cPanel "Web sites IP".
user: This user must to have permissions to access (You can add this permission in MySQL Databases menu in cPanel).
database: Name database.
Note: Add permission for your IP in Remote MySQL Menu in cPanel
You can use sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://user:password#host/database')
conn = engine.connect()

Categories

Resources