db.create_all() doesn't create a database [duplicate] - python

I am using the following code to create postgresql database using sqlalchemy:
engine=create_engine('postgresql+psycopg2://postgres#localhost/testData')
Base.metadata.create_all(engine)
But it gives me the following error even though I manually created the database in psql:
File "/home/ubuntu/venve/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 376, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/home/ubuntu/venve/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
sqlalchemy.exc.OperationalError: (OperationalError) FATAL: database "testData" does not exist
Why is this happening?

You need to create the database beforehand, create_all just creates the tables. To create database: sudo -u postgres createdb testData.

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.

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

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

Django won't connect to remote RDS

When I run 'python manage.py runserver', I get:
File
"/Users/myusername/.virtualenvs/dashboard-server-PG7390RB/lib/python3.6/site-packages/django/db/backends/postgresql/base.py",
line 176, in get_new_connection
connection = Database.connect(**conn_params) File "/Users/myusername/.virtualenvs/dashboard-server-PG7390RB/lib/python3.6/site-packages/psycopg2/init.py",
line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync) " to address: nodename nor servname provided, or not known name "rdsaddress.us-east-1.rds.amazonaws.com
This happened when I updated iterm2, but downgrading did not fix it.
I am able to successfully connect to the database using Postico.
I am unable to connect to a similar rds using Django as well.
I deleted my repository and repulled...
Not sure what to do next.
Hard to say without seeing your connection code, but it should look a little like this:
conn = psycopg2.connect("dbname=your_database user=postgres password=xxxx host=127.0.0.1 port=5432")
The error complains about nodename nor servername provided, hence my inclination to look at your connection string.

Heroku MySQL DB Error with Flask

I'm trying to host a local MySQL database using ClearDB on Heroku. The build is successful, but when I try to access the application, the application fails.
Here is my app.py code (it fails on the first line):
db = MySQLdb.connect(host="localhost", user="root", db="database")
cur = db.cursor()
query = """SELECT * from database"""
cur.execute(query)
data = cur.fetchall()
Here is the log output:
2016-06-01T14:48:48.720931+00:00 heroku[web.1]: Starting process with command `python app.py`
2016-06-01T14:48:51.790883+00:00 app[web.1]: File "app.py", line 30, in <module>
2016-06-01T14:48:51.790864+00:00 app[web.1]: Traceback (most recent call last):
2016-06-01T14:48:51.790910+00:00 app[web.1]: db = MySQLdb.connect(host="localhost", user="root", db="database")
2016-06-01T14:48:51.790981+00:00 app[web.1]: _mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
2016-06-01T14:48:51.790911+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
2016-06-01T14:48:51.790912+00:00 app[web.1]: return Connection(*args, **kwargs)
2016-06-01T14:48:51.790912+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__
2016-06-01T14:48:51.790937+00:00 app[web.1]: super(Connection, self).__init__(*args, **kwargs2)
2016-06-01T14:48:52.491629+00:00 heroku[web.1]: Process exited with status 1
Here is what heroku config prints:
CLEARDB_DATABASE_URL: mysql://actualurl
DATABASE_URL: mysql://actualurl
MYSQL_DB: database
MYSQL_HOST: localhost
MYSQL_USER: root
There's no point in posting your Heroku config, because it's clear that your app isn't using it. You have hardcoded the database host as "localhost", rather than using the DATABASE_URL environment variable.

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