3.6 Selecting and opening the table in mysql
Selecting and opening the table: -
- To view the records from the table, we use “SELECT” statement.
- Import mysql.connector.
- Connect to MySQL database using connect( ) method.
- Create a cursor( ) object then pass SQL select query command as a string to the execute( ) method.
- Use fetchall( ) of cursor object to display all records in table.
- To display all records from table, we use for loop in python.
- The SQL command to select all the records from the table in database with python code is:
Example: -
output: -
- To display specific records from table, we use where clause. It filters the data as per the condition. We can fetch, delete or update a set of data in MySQL database.
- The SQL command to select specific records from the table in database with python code is:
output: -
Using the ORDER BY clause: -
- Order By clause is used to arrange the results set in either ascending or descending order.
- By default, it is ascending order unless “DESC” is mentioned which is arrange the results in descending order.
- The SQL command to arrange the records in order with python code is:
Example: -
Output:
-