Python MySQL – Select Query
Python MySQL – Select Query
Here is a Python example to perform a SELECT
query from a MySQL database using the mysql-connector-python
library:
Step 1: Install the Required Library
If you haven't already installed the library, run:
Step 2: Example Code for SELECT
Query
Explanation:
Connection Setup:
- Use
mysql.connector.connect()
to connect to your MySQL database. - Specify host, user, password, and database parameters.
- Use
Cursor Execution:
- Create a cursor object with
connection.cursor()
. - Execute the
SELECT
query usingcursor.execute(query)
.
- Create a cursor object with
Fetching Data:
- Use
cursor.fetchall()
to retrieve all rows from the executed query. - Each row is a tuple containing the selected columns.
- Use
Error Handling:
- The
try-except
block handles database connection or execution errors.
- The
Cleanup:
- Close the cursor and connection in the
finally
block to ensure proper resource management.
- Close the cursor and connection in the
Output Example:
Assume the table your_table
contains:
id | name | age |
---|---|---|
1 | Alice | 25 |
2 | Bob | 30 |
The output will be:
Let's Have A Practical Example
http://localhost:81/python/hi.py open in browser(WAMP + MYSQL CONNECTOR INSTALLED USING PYTHON THEN WORK)
http://localhost:81/python/hi.py open in browser(WAMP + MYSQL CONNECTOR INSTALLED USING PYTHON THEN WORK)
The cursor.MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where,
The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones).
The fetchone() method fetches the next row in the result of a query and returns it as a tuple.
The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row.
Comments
Post a Comment