import psycopg2
from passlib.hash import bcrypt
#from config import host, user, password, db_name
try:
# connect to the existing database
connection = psycopg2.connect(
host="127.0.0.1",
user="user",
password="123a",
database="postgres3"
)
connection.autocommit = True
with connection.cursor() as cursor:
cursor.execute(
"SELECT version();"
)
print(f"Server version: {cursor.fetchone()}")
# Generate a strong password
from passlib import pwd
strong_password = pwd.genword(length=15, charset='ascii_letters' + 'digits' + 'punctuation')
# Hash the password using bcrypt
hashed_password = bcrypt.hash(strong_password)
with connection.cursor() as cursor:
cursor.execute(
"CREATE TABLE users(id serial PRIMARY KEY, username varchar(50) NOT NULL, password varchar(255) NOT NULL);"
)
with connection.cursor() as cursor:
cursor.execute(
"INSERT INTO users (username, password) VALUES ('admin', %s);",
[hashed_password]
)
print(f"[INFO] Data was successfully inserted, generated password: {strong_password}")
with connection.cursor() as cursor:
cursor.execute(
"SELECT * FROM users;"
)
print("User info from the database:")
for row in cursor.fetchall():
print(row)
with connection.cursor() as cursor:
cursor.execute(
"DROP TABLE users;"
)
print("[INFO] Table was deleted")
except Exception as ex:
print("[INFO] Error while working with PostgreSQL", ex)
finally:
if connection:
connection.close()
print("[INFO] PostgreSQL connection closed")
code error:
Server version: ('PostgreSQL 16.2, compiled by Visual C++ build 1925, 64-bit',)
[INFO] Error while working with PostgreSQL 'ascii_lettersdigitspunctuation'
[INFO] PostgreSQL connection close
The code should create a strong password and encrypt it and enter it into the database. The postgresql server is running, but it does not connect to it and gives an error. What could be causing this and how can I fix it? Changing the encoding in the database did not help.
Lesh 1337 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.