Hello everyone. This post has two sides and its kinda long:
Part I:
First, about some errors and overall understanding of the connection to PostgreSQL with psycopg:
My installation process was this one (on ubuntu 20.04):
- pip3 install psycopg2 (resulted in some errors, which were corrected by step 2)
2.sudo apt-get install libpq-dev and then pip3 install psycopg2
3.psql command gave the following error: psql: error: could not connect to server: FATAL: role “samyr” does not exist. (samyr is the current computer user)
- sudo -u createuser samyr Now psql gives another error psql: error: could not connect to server: FATAL: database “samyr” does not exist which makes sense because by default (if I’m not mistaken psql uses the same string for the user and db, so I only solved one of the problems)
5.I try the following code:
import psycopg2
conn = psycopg2.connect(dbname="postgres", user="postgres")
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("CREATE TABLE notes(id integer PRIMARY KEY, body text, title text)")
conn.close()
Which gives the following error: FATAL: Peer authentication failed for user "postgres"
So I change the user argument to “samyr” which works. But for some reason that I cant understand, when I tried to create another users such as “testuser” using the same method (sudo -u postgres createuser testuser) it gives error: FATAL: Peer authentication failed for user “testuser”.
- I tried the following code:
import psycopg2
conn = psycopg2.connect(dbname="postgres", user="samyr")
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("CREATE TABLE testtable(id integer PRIMARY KEY, body text, title text)")
cursor.execute("INSERT INTO testtable values (1,'Hello','Dataquest');")
x=cursor.execute("SELECT * FROM testtable;")
print(x)
conn.close()
Which returns “None” .
All of this was to give context for my questions:
Step 4. This isn’t how we learned how to create users, when should we use this method?
Step 5. The ‘‘postgress’’ db is a db that anyone in the whole world can try to access? Or is it only on my machine? Why did the peer authentication only worked for the user ‘‘samyr’’ and not for ‘‘testuser’’?
Step 6. Why is the code returning None?
Part II:
The next mission is regarding indexes using SQLite. So I’m left with the feeling of no closure in the matter. When should I use psql through the command line and when should I use it within python? And more importantly: What can I do with PostgreSQL on my own? Or will I only use it in a large company that uses it? Are there any databases that I can access on my own?
Thank you for reading so far, and I hope this doesn’t sound overly picky.