QBoard » Advanced Visualizations » Viz - Python » Using MySQL commands in Python

Using MySQL commands in Python

  • I just got into SQL to do some data science and was wondering why my code was running but not affecting the MySQL database in any way. I am using pycharm and the MySQLdb module.

     import MySQLdb
     db = MySQLdb.connect(host="localhost",
                          user="root",
                          passwd="********", #Password blocked
                          db="test")
     cur = db.cursor()
     cur.execute("SELECT * FROM movies")
     cur.execute("Update movies set genre = 'action' where id = 1")
     for row in cur.fetchall() :
         print row[0], " ", row[1], " ", row[2]

     

    My code runs and returns no errors, but when I delete the

     cur.execute("Update movies set genre = 'action' where id = 1")
    

     

    line it just prints out the table the as it was before. Just for reference, here is the table:

    1 Interstellar sci-fi

    2 Thor: Ragnarok action

    3 Thor: The Dark World action

    How can I make the commands in python actually affect the table? Thank you so much for your help!

      December 23, 2021 2:19 PM IST
    0
    1. Connect to the MySQL Database, you get a MySQLConnection object.
    2. Instantiate a MySQLCursor object from the the MySQLConnection object.
    3. Use the cursor to execute a query by calling its execute() method.
      December 27, 2021 12:09 PM IST
    0
  • You have to commit changes made to the table using cur.commit()

    Database does not update automatically with MySQL and Python

      January 1, 2022 2:10 PM IST
    0