python-mysqlHow can I connect Python to a MySQL database using an ODBC driver?
To connect Python to a MySQL database using an ODBC driver, you need to install the relevant ODBC driver for the database you are using. For example, if you are using MySQL, you can install the MySQL ODBC driver. Once you have installed the driver, you can use the pyodbc
library to connect to the database.
Example code
import pyodbc
# Connect to the database
connection = pyodbc.connect("DRIVER={MySQL ODBC Driver};SERVER=localhost;DATABASE=my_database;UID=user;PWD=password")
# Execute a query
cursor = connection.cursor()
cursor.execute("SELECT * FROM my_table")
# Fetch the results
rows = cursor.fetchall()
# Print the results
for row in rows:
print(row)
Output example
('John', 'Doe', '[email protected]')
('Jane', 'Doe', '[email protected]')
Code explanation
import pyodbc
- imports thepyodbc
library which is used to connect to the database.connection = pyodbc.connect("DRIVER={MySQL ODBC Driver};SERVER=localhost;DATABASE=my_database;UID=user;PWD=password")
- connects to the database using the ODBC driver. The string contains the necessary connection parameters such as the driver, server, database, user and password.cursor = connection.cursor()
- creates a cursor object which is used to execute queries on the database.cursor.execute("SELECT * FROM my_table")
- executes a query on the database.rows = cursor.fetchall()
- fetches the results of the query.for row in rows: print(row)
- prints the results of the query.
Helpful links
More of Python Mysql
- How do I use Python to connect to a MySQL database using XAMPP?
- How do I check the version of MySQL I am using with Python?
- How do I use Python to update multiple columns in a MySQL database?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I connect Python to a MySQL database?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I avoid MySQL IntegrityError when using Python?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use the WHERE IN clause in Python to query a MySQL database?
- How do I set up a secure SSL connection between Python and MySQL?
See more codes...