DEV Community

loading...
Cover image for Modify or Update live database in Python and Django

Modify or Update live database in Python and Django

Shivam Rohilla
Talk is cheap. Show me the code
・1 min read

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

then execute a update command

cur.execute("UPDATE auth_user SET email = LOWER(email) WHERE email != LOWER(email);")
Enter fullscreen mode Exit fullscreen mode

after then commit this

conn.commit()
Enter fullscreen mode Exit fullscreen mode

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

cur.execute("SELECT * from auth_user")
rows = cur.fetchall()
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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

print("Complete")
Enter fullscreen mode Exit fullscreen mode

then close the connection.

conn.close()    
Enter fullscreen mode Exit fullscreen mode

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

python update.py
Enter fullscreen mode Exit fullscreen mode

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

Thank You
Shivam Rohilla | Python Developer

Discussion (0)