To run a Python script that accesses a database on dcm.uhcl.edu

T.A. Yang

·        The following prerequisites must be met in order to run exercises included in this tutorial:

 

a)      Check out the instructions in Creating your own toyu database to learn how to create your own toyu database using a SQL script file.

Note: Your account id is your last name followed by the first letter of your first name. For example, John Doe’s account name is doej.

The password is Sce+your id + !! (e.g., Sce1234567!!, if the person’s id is 1234567.

b)     Make sure your computer has a Python package installed. Check out the instructions given in To run a Python script on your computer.

 

c)      On your own computer, you will need to have a database connector installed in order for your Python script to communicate with the MySQL databases on the server.

 

There exist more than one type of database connectors for Python to connect to a MySQL server. In this demonstration, we use the Python MySQL connector.

 

Below are different methods that you may use to get the MySQL connector installed on your own computer.

§  Method 1: Use the pip application that comes with your Python package to install the database connector.

 

§  Method 2: Download and install the MySQL Installer for Python (available at https://dev.mysql.com/downloads/connector/python/) in order to install the database connector.

 

§  Method 3: Alternatively, the Python MySQL connector (and other connectors as well) can be downloaded by installing the MySQL installer. Check out the download link at https://dev.mysql.com/downloads/installer/ (MySQL Installer 8.0.33).

 

To see if a given computer has the Python MySQL connector successfully installed:

      - Open a Command Prompt window; enter the command python.

      - Enter import mysql following the python prompt. If no error message is returned, the MySQL connection is properly installed.

 

 

Useful resources about MySQL database connectors and Python scripts:

-        https://www.youtube.com/watch?v=vR5utJvN4JY

-        https://www.youtube.com/watch?v=3vsC05rxZ8c

 

 

 

·        Download this sample Python script, mysqlPython.py, make necessary modifications (i.e., user name, password, and database name), and save it as a Python script file.

 

·        Open a Command Prompt and enter the command python mysqlPython.py to run the script. As shown below, the Python script connects to the c433323su01yangt2 database on dcm.uhcl.edu, select the tuples from the Student table, and then enters a while loop to print each of the tuples. After that, the database connection is closed.