pymysql.err.InternalError: (1049, "Unknown database") - python

I want to connect MySQL RDS DB using python from raspberrypi.(i want to get seq from MySQL table 'face' using select query.)
and I have an error but i can not fix it.
This is rds mysql connection code:
import rds_config
import pymysql
rds_host = rds_config.rds_host
name = rds_config.rds_user
password = rds_config.rds_pwd
db_name = rds_config.rds_db
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name,
connect_timeout=10)
with conn.cursor() as cur:
cur.execute("select seq from face")
conn.commit()
rds_config:
rds_host='rds endpoint'
rds_port=3306
rds_user='user'
rds_pwd='password'
rds_db='db name'
and This is traceback:
Traceback (most recent call last):
File "getRds.py", line 18, in <module>
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=10)
File "/usr/local/lib/python2.7/dist-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 327, in __init__
self.connect()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 598, in connect
self._request_authentication()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 862, in _request_authentication
auth_packet = self._process_auth(plugin_name, auth_packet)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 933, in _process_auth
pkt = self._read_packet()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 683, in _read_packet
packet.check_error()
File "/usr/local/lib/python2.7/dist-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/usr/local/lib/python2.7/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.InternalError: (1049, u"Unknown database 'bsb-rds'")
i alread added ip address in vpc security group and public access is on.
it was possible to connect through mysql cli or workbench.
can anyone help me?

tl;dr you need to create bsb-rd. Execute this command: create database bsb-rds either with cur.execute() in python or in your favorite sql cli.
If you get this error, good news! You can connect to your RDS instance. This means you have the security group set up right, the host url, username, password and port are all correct! What this error is telling you is that your database bsb-rds does not exist on your RDS instance. If you have just made the RDS instance it is probably because you have not created the database yet. So create it!
Here are two ways to do this
mysql cli
In your terminal run
mysql --host=the_host_address user=your_user_name --password=your_password
Then inside the mysql shell execute
create database bsb-rd;
Now try your code again!
Python with pymysql
import rds_config
conn = pymysql.connect('hostname', user='username', passwd='password', connect_timeout=10)
with conn.cursor() as cur:
cur.execute('create database bsb-rd;')
I came to this page looking for a solution and didn't get it. I eventually found the answer and now share what helped me.

I ran into your exact issue and I believe I have the solution:
Context:
My tech stack looks like the following
Using AWS RDS (MySQL)
Using Flask Development on local host
RDS instance name: "test-rds"
Actual DB Name: test-database
Here is where my issue was and I believe your issue is in the same place:
You are using the AWS RDS NAME in your connection rather than using the true Database name.
Simply changing the DB name in my connection to the true DB name that I had setup via MySQL Workbench fixed the issue.
Other things things to note for readers:
Please ensure the following:
If you are connecting from outside your AWS VPC make sure you have public access enabled. This is a huge "gotcha". (Beware security risks)
Make sure your connection isn't being blocked by a NACL
Make sure your connection is allowed by a Security Group Rule

Related

SELECT command denied to user (even though I have all privileges)

I host on godaddy.com and after multiple calls they ensured me that I have done right everything when it comes to the database setup. The account "python" has all necessary rights to fulfil its purpose.
import mysql.connector as sql
mydb = sql.connect(
host = "***.***.***.***",
user = "python",
passwd = "*******",
db = "main"
)
print(mydb)
sql_select_Query = "select * from wp_posts.wp_content"
cursor = mydb.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
print(cursor.rowcount)
On phpmyadmin Im not able to do anything. I can't grant any rights. When I execute the code, the following error occurs.
<mysql.connector.connection.MySQLConnection object at 0x7fddb0053610>
Traceback (most recent call last):
File "Untitled 2.py", line 12, in <module>
cursor.execute(sql_select_Query)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1142 (42000): SELECT command denied to user 'python'#'p579F3618.dip0.t-ipconnect.de' for table 'wp_content'
The connection is established, but the database doesn't grant any access. I have the right to login, but nothing more.
Solutions I tried, but that failed:
godaddy support is clueless (they say it should work perfectly)
granting me rights through phpmyadmin (don't have any privilege to do that)
added my IP address into the Remote Hosting Option in cPanel (now im able to establish a connection, but nothing more)
Maybe helpful:
On phpmyadmin im automatically logged in into an account that ends with #localhost. This account has the select privilege, but I can't access its password and therefore can't use it in python.

Python mysql connector change host link to ipaddress

I am coming across an issue with mysql connector.
I have an environment that i can't connect from my local machine.
I use simple command for connection:
from mysql.connector import connect
connection = mysql.connector.connect(user='dbuser', database='dbname',
host='amazon_link', password='dbpassword')
This works for all environment except one. And this also works in the server as well where the database lives.
I can access the database using my MySqlWorkbench from local machine. But when i try from my script, i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 210, in _open_connection
self._ssl)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 144, in _do_auth
self._auth_switch_request(username, password)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 177, in _auth_switch_request
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'dbuser'#'10.0.1.72' (using password: YES)
And the ip address that i get for the host link is different from what mysql connector is showing here as well.
Is there a way to avoid mysql connector to change link to url here, as when i use the link instead of ip address in my Workbench i am able to connect. So i doubt it is an issue related to vpn or security groups. Otherwise i wouldn't be able to connect to database via work bench at all.
Any help would be appreciated. Thanks.
And sorry in case i missed something basic here.
Try to use the global IP address of your server instead of the domain name.
Refer the stackoverflow link for more details:
Remotely connect to MySQL with Python mysql.connector

Required field 'sessionHandle' is unset! while using hive with python

I have tried various approach of using hive with python.
One is
How to Access Hive via Python?
Also tried https://sites.google.com/site/tingyusz/home/blogs/hiveinpython
Where I am getting
File "py_hive.py", line 8, in <module>
database='default') as conn:
File "/home/karimk/python/lib/python2.7/site-packages/pyhs2/__init__.py", line 7, in connect
return Connection(*args, **kwargs)
File "/home/karimk/python/lib/python2.7/site-packages/pyhs2/connections.py", line 52, in __init__
cur.execute(query)
File "/home/karimk/python/lib/python2.7/site-packages/pyhs2/cursor.py", line 61, in execute
res = self.client.ExecuteStatement(query)
File "/home/karimk/python/lib/python2.7/site-packages/pyhs2/TCLIService/TCLIService.py", line 244, in ExecuteStatement
return self.recv_ExecuteStatement()
File "/home/karimk/python/lib/python2.7/site-packages/pyhs2/TCLIService/TCLIService.py", line 260, in recv_ExecuteStatement
raise x
thrift.Thrift.TApplicationException: Required field 'sessionHandle' is unset! Struct:TExecuteStatementReq(sessionHandle:null, statement:USE default, confOverlay:{})
Python code:
import pyhs2
with pyhs2.connect(host='dmeet-master02.inetuhosted.net',
port=10000,
authMechanism="PLAIN",
user='userk',
password='userk',
database='default') as conn:
with conn.cursor() as cur:
#Show databases
print cur.getDatabases()
#Execute query
cur.execute("select * from table")
#Return column info from query
print cur.getSchema()
#Fetch table results
for i in cur.fetch():
print i
break
any hint on this?
I am using a similar initialization code for connecting with Hive and it works for me.
But, I can see that it's failing to initialize the connection.
The field sessionHandle is set internally while opening connection with the server. It is unset (or set to None) when corresponding socket connection can't be opened. Try reaching without specifying a database and see if it works.

pymysql cannot connect with SSL

I am trying to connect to a MySQL database using python but I am getting a strange error. It is compounded by the fact that I can use the same connection values from the mysql console command and it connects with no problems.
Here is the exact code I am using:
import pymysql
from checks import AgentCheck
class DelayedJobCheck(AgentCheck):
def check(self, instance):
self.log.info("testing connection")
self.log.info(instance)
connection = pymysql.connect(**instance)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()
self.gauge('hello.world', 1)
This is the error that I am getting:
Traceback (most recent call last):
File "/opt/datadog-agent/agent/checks/__init__.py", line 661, in run
self.check(copy.deepcopy(instance))
File "/opt/datadog-agent/agent/checks.d/delayed_job.py", line 10, in check
connection = pymysql.connect(**instance)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
OperationalError: (2003, u"Can't connect to MySQL server on '192.168.199.86' ([SSL: SSL_NEGATIVE_LENGTH] dh key too small (_ssl.c:590))")
I am running this code on a Ubuntu box and I though initially that it might be because the SSL CA is a self generated cert. So I followed the steps here But, it did not make any difference. Also I have verified that the process that is running this code has full access to the cert files
Any ideas what else might be causing this?
As the err info said dh key is too small, a larger one might help. Replace the default dh512.pem file with dh4096.pem
sudo wget "https://git.openssl.org/gitweb/?p=openssl.git;a=blob_plain;f=apps/dh4096.pem" -O dh4096.pem
Ref: http://www.alexrhino.net/jekyll/update/2015/07/14/dh-params-test-fail.html

Python SQL connect to wrong ip adress

I'm trying to connect to my sql server using a simple python script.
import MySQLdb
db = MySQLdb.connect(host="192.168.0.156", user="root",
passwd="Imnottellingyoumypassword", db="mydatabase") # name of the data base
cur = db.cursor()
cur.execute("SELECT * FROM customers")
for row in cur.fetchall() :
print row[0]
But when I run my script something goes wrong:
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user
'root'#'192.168.0.107' (using password: YES)")
Why is he trying to connect to my ip address of my laptop instead of the sql server?
That message is from the MySQL server and not the MySQL driver. What the server is telling you is that connections as root from the IP of your laptop aren't allowed.

Categories

Resources