import psycopg2
import time
# Database connection details
db_config = {
'dbname': 'users', # Name of the database
'user': 'your_username', # Replace with your PostgreSQL username
'password': 'your_password', # Replace with your PostgreSQL password
'host': 'localhost', # Replace with your host if needed
'port': '5432' # PostgreSQL default port
}
# Function to connect to the PostgreSQL database
def connect_to_db(config):
try:
conn = psycopg2.connect(**config)
print("Connection established.")
return conn
except Exception as error:
print(f"Error connecting to the database: {error}")
return None
# Function to perform the updates
def perform_updates(conn):
try:
cursor = conn.cursor()
for i in range(10):
print(f"Iteration {i+1}/10")
# Step a.i: Append 'ccc' to plain_text
append_query = """
UPDATE dbo.paragraph
SET plain_text = plain_text || 'ccc'
WHERE id IS NOT NULL;
"""
cursor.execute(append_query)
conn.commit() # Commit the change
print("Appended 'ccc' to plain_text")
# Wait for 5 seconds
time.sleep(5)
# Step c.i: Remove the last 3 characters from plain_text
remove_query = """
UPDATE dbo.paragraph
SET plain_text = substring(plain_text FROM 1 FOR length(plain_text) - 3)
WHERE id IS NOT NULL;
"""
cursor.execute(remove_query)
conn.commit() # Commit the change
print("Removed last 3 characters from plain_text")
except Exception as error:
print(f"Error performing updates: {error}")
conn.rollback() # Rollback in case of an error
finally:
cursor.close()
# Main execution
if __name__ == "__main__":
# Connect to the database
connection = connect_to_db(db_config)
if connection is not None:
# Perform the updates in a loop
perform_updates(connection)
# Close the connection
connection.close()
print("Connection closed.")