Why is my created postgres user being denied access to a table? - python

I have created a user for my Postgres database but I cannot access the data with the user that I set up.
In a python shell I have run the following code:
>>> import psycopg2
>>> conn=psycopg2.connect(
database="db",
user="postgres",
host="/tmp/",
password="opensesame"
)
>>> cur = conn.cursor()
>>> state = 'Arkansas'
>>> cur.execute("SELECT city FROM table WHERE state = %s", (state,))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
cur.execute("SELECT city FROM table WHERE state = %s", (state,))
ProgrammingError: permission denied for relation table
As the superuser, I have tried:
db=# ALTER USER postgres SET TO default
but it did not help
I need to get this user access to this table, any help would be appreciated. Thank you for viewing.

try this,
log into postgres
sudo -u postgres psql
then enter \l it will list all the tables, you will see a list of your created databases,
then
GRANT ALL ON db TO postgres;
if all goes well you should now do \l again and see that you are now privileged.

In my code, I was receiving the error message:
ProgrammingError: permission denied for relation author
Although:
GRANT ALL ON db TO postgres;
may resolve this error for some, I later located:
Permission denied for relation
and found that you may want to name the relation, sequence or table instead of the DB. According to the link above, granting privilege on the DB might have more to do with accessing the connection, rather than sort of recursively going through the tables, relations and sequences and granting privilege on all of them.
At the very least, if you run into this error, read both this article and that one and see if either one resolves the problem.

Related

Pulling Snowflake table into Dataframe

I continue to get and error "ProgrammingError: 002003 (42502): SQL compilation error: Object 'Table' does not exist or not authorized. I am using the following code:
con = snowflake.connector.connect(
user = "user.name",
authenticator="externalbrowser",
warehouse = "ware house name",
database = "db name",
schema = "schema name"
)
cur.con.cursor()
sql = "select * from Table"
cur.execute(sql)
df = cur.fetch_pandas_all()
When I execute the code in Jupyter Notebook the browser window opens and authenticates my creds but when it gets to the sql execute line the error rises and tells me that the table does not exist. When I open up Snowflake in my browser I can see that the table does exist in the correct warehouse, database and schema I have in my code.
Has anyone else ever experienced this? Do I need to authorize my user to be able to access this table via Python and Jupyter Notebook?
It's likely your session doesn't have a role assigned to it (current role).
You can add the role in your list of connection session paramters,
e.g. add something like the following
role = 'RICH_ROLE',
You might want to consider setting a default role for your user.
ALTER USER userNameHere SET DEFAULT_ROLE = 'THE_BEST_ROLE';
docs link: https://docs.snowflake.com/en/sql-reference/sql/alter-user.html
Also, when all else fails, use the fully qualified table name, note this won't help much if the role isn't set:
sql = "select * from databaseName.schemaName.TableName"

Remote Postgresql Query - Permission denied for table xxxx

Struggling to remotly query a postgres database.
I've populated the /etc/postgresql/12/main/pg_hba.conf / postgresql.conf with the correct information.
I know I can query remotely as its working from within PyCharm.
But EVERY time I try this command I'm getting an error
conn = psycopg2.connect(host="******", database="******", user="******", password="********")
cur = conn.cursor()
cur.execute(f"""select id, login_count, orders from "user" where account = '{account}' """)
ERROR:
permission denied for table user
Postgresql log:
2021-09-08 23:03:52.353 UTC [11354] colemanbros#colemans ERROR: permission denied for table user
2021-09-08 23:03:52.353 UTC [11354] colemanbros#colemans STATEMENT: select * from "user"
The login credentials for both pycharm and psycopg2 are the same. And both are being run from my local machine.
Psycopg2 on jupyter
Pycharm is connecting to the database with jdbc
Can anyone offer some insight into why this might be?

Error in database connection: Database "dbname" does not exist

I have created a python file app.py and included the code to connect to a db I created in postgresql as follows: -
import psycopg2
conn = psycopg2.connect(
user='postgres',
password='1234',
host='localhost',
port='5432',
database='bubbleformation'
)
cursor = conn.sursor()
cursor.execute('SELECT * FROM bubbleformation')
for row in cursor: print(row)
conn.close()
This was as instructed in this medium article
However, when I try to execute this python file in the terminal, I get the below error: -
Traceback (most recent call last): File "app.py", line 8, in
port='5432' File "/usr/lib/python2.7/dist-packages/psycopg2/init.py", line 130, in
connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: database "bubbleformation" does not exist
I have created a table named "bubbleformation" and it can be viewed in the psql mode through the terminal.
Could anyone please help me understand what should be done? I tried changing the password, and user privileges, but none of them worked for my error.
You should create both database and table with the same name "bubbleformation". You've probably created that table in postgres database.
Enter psql as postgres user and call CREATE DATABASE bubbleformation;, then connect to it with \connect bubbleformation and then create your table (something like CREATE TABLE bubbleformation (id int, name text);).
The error is about there not being a database named "bubbleformation", so when you connect to the database in the terminal, whichever database that is is the one you need to specify in the database parameter. When you connect to the database in the terminal, type:
SELECT current_database();
If it is indeed a database named "bubbleformation" then is must be a different cluster you are connecting to, and therefore a different port.
Disclosure: I am an EnterpriseDB (EDB) employee.
Its due to environment error. I was loading the credentials from the .env file. But i mistakenly gave a wrong path.
project_folder = os.path.expanduser('~/scraping') instead of
project_folder = os.path.expanduser('~/find_my_nearest_store')
load_dotenv(os.path.join(project_folder, '.env'))
Hence the Error.

Why am I getting peer authentication failed error when trying to connect using psycopg2?

So I have a successful install of Postgres on Ubuntu and am trying to do some basic connection and creating a table in a db using another username other than the default (postgres) and coming up short. From what I can gather I think it may have something to do with permissions? What I want is to be able to use some superuser other than postgres to create tables and do stuff.
"psql example3" and "\l" shows the example3 db was created successfully. I now have a list of databases include the default postgres, template0, template1 and example3 all with owner as postgres. What I run into problems then is running demoscript.py gives a fatal "peer authentication failed for user 'thisuser'"
#Create the db and user with superuser permissions
sudo -u postgres -i
createdb example3
createuser --interactive --pwprompt
#role:thisuser
#pwd:thispass
#superuser?:Y
#demoscript.py
import psycopg2
connection = psycopg2.connect('dbname=example3 user=thisuser password=thispass')
cursor = connection.cursor()
cursor.execute('DROP TABLE IF EXISTS todos;')
cursor.execute('''
CREATE TABLE todos(
id serial PRIMARY KEY,
description VARCHAR NOT NULL
);
''')
connection.commit()
cursor.close()
connection.close()
Expected result is that the todos table should show as created after looking for it in the example3 db. But I just get the fatal error.
When you don't specify a host in your connection, it tries to connect via Unix sockets. By default, PostgreSQL is set up to use peer authentication on those, which means it compares the PostgreSQL username to the currently logged in OS user. If you change your connection to:
connection = psycopg2.connect('dbname=example3 user=thisuser password=thispass host=localhost')
that should cause it to use the authentication settings for TCP/IP connections, which default to password authentication on most systems I've used.

Python connecting to MySQL database name error

I got the following code from this site to connect to a mysql database through python (which is much appreciated by the way). I have used it once already to connect to a database on the server, but in a different file. However I know want to connect to another database on the same server but i keep getting error message to do with the database name.
I am using exactly the same code as I was before to connect, however i have only changed the database name to the other one i want to connect to. I can look at the database through puTTY, and see that it is called the correct name and that all the data is there, but just cant seem to connect properly through the Python.
Thanks in advance for any help!
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", # your host, usually localhost
user="root", # your username
passwd="........", # your password
db="opt_out") # 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 opted_in")
# print all the first cell of all the rows
for row in cur.fetchall() :
print row[0]
And this is the error code i get in return when i try and execute the python file through puTTY:
Traceback (most recent call last):
File "/var/www/html/vra/ConnectAdiDB.py", line 7, in <module>
db="opt_out") # name of the data base
File "/usr/lib64/python2.6/site-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'#'localhost' (using password: YES)")
The Password must be wrong (I Think so)
So Try to reset the password so:
first off turn of the mysql Service like so
Ubuntu/Debian:
sudo service mysql stop
After That Do So:
sudo service mysql start
When Done Start mysql like so:
sudo mysql
An execute:
UPDATE mysql.user SET Password=PASSWORD('NEW-PASSWORD') WHERE User='root';
FLUSH PRIVILEGES;

Categories