Modify or Update live database in Python and Django

Hello guys, in this post I'm gonna tell you about how to update the live database in Python and Django, you'll see in this blog how to connect with the live database and update or modify that. we update and convert all the emails into lowercase. We'll use LOWER(column) function for converting all the emails into the lowercase.

pip install psycopg2

Psycopg2 is used to implement a connection pool.

Make a connection and enter your database name and credentials or host and password.

conn = psycopg2.connect(
    database = "dindin",
    user="postgres",
    host="localhost",
    port="5432",
    password="Shivam123",

)

cur = conn.cursor()

then execute a update command

cur.execute("UPDATE auth_user SET email = LOWER(email) WHERE email != LOWER(email);")

after then commit this

conn.commit()

then use the select command and select all the users from your table name

cur.execute("SELECT * from auth_user")
rows = cur.fetchall()

and then print all the user details you want to print or want to know that your emails are converted successfully or not. Use these print commands, and please write their indexes carefully otherwise it shows errors.

for row in rows:
    print("ID :", row[0] )
    print("username :", row[4] )
    print("email :", row[7] )
    print("/n")

and print this command for checking your program compiled successfully or not.

print("Complete")

then close the connection.

conn.close()

and name this file as update.py and run this program in your terminal

python update.py

after running this command you will see the complete message in your terminal.

Thank You
Shivam Rohilla | Python Developer

22