Python-MySQL Connection


  1. Check the Python Help Pages.

  2. Apply for a UND Engineering Linux Account.

  3. Use VPN (Virtual Private Network) to connect to the UND networks.
  4. You may not need to do this if you are on campus.

  5. Log in to the Linux server undcemcs02.und.edu .

  6. Execute the following command:
  7.    shell⯈ pip install mysql-connector-python 
    where
    • pip (PIP Installs Packages) is a package management system used to install and manage software packages written in Python and

    • mysql-connector-python is an official API (Application Programming Interface) provided by MySQL that enables Python programs to connect to and interact with MySQL databases.

  8. Create a Java script such as py-mysql.py:

  9. #!/usr/bin/python
    
    import mysql.connector
    
    # Establish the connection
    try:
      connection = mysql.connector.connect (
        # Replace with your MySQL server host
        host="undcemmysql.mysql.database.azure.com",
        # Replace with your MySQL username
        user="user_id",
        # Replace with your MySQL password
        password="p-word",
        # Replace with your database name
        database="user_id"
      )
      if connection.is_connected( ):
        print( "Connected to MySQL database" )
    
      # Create a cursor object
      cursor = connection.cursor( )
    
      # Execute a query
      # Replace 'your_table' with your table name
      cursor.execute( "SELECT * FROM course" )
    
      # Fetch and display the results
      results = cursor.fetchall( )
      for row in results:
        print( row )
    
    except mysql.connector.Error as err:
      print(f"Error: {err}")
    
    finally:
      # Close the connection
      if connection.is_connected( ):
        cursor.close( )
        connection.close( )
        print( "MySQL connection is closed" )

  10. Compile and run the script.
  11. For example,
       shell⯈ /usr/bin/python  py-mysql.py