Certainly! Here's an example of a Python script that demonstrates how to use the ODBC connector to connect to a database and execute a query:
import pyodbc
# Set up ODBC connection parameters
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'
driver = '{ODBC Driver 17 for SQL Server}' # Update the driver based on your database type
# Establish the ODBC connection
connection_string = f"DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}"
conn = pyodbc.connect(connection_string)
# Create a cursor object to interact with the database
cursor = conn.cursor()
# Execute a sample query
query = 'SELECT * FROM your_table_name'
cursor.execute(query)
# Fetch and print the query results
for row in cursor:
print(row)
# Close the cursor and the connection
cursor.close()
conn.close()
Make sure to replace `'your_server_name'`, `'your_database_name'`, `'your_username'`, `'your_password'`, and `'your_table_name'` with the appropriate values for your database setup. Additionally, update the `'driver'` value based on the type of database you're connecting to.
This script uses the `pyodbc` library, which provides a Python DB API 2.0 interface for ODBC connections. You may need to install `pyodbc` using `pip install pyodbc` before running this script.
Please note that this is just a basic example to get you started. Depending on your specific requirements and the database you're connecting to, you may need to modify the code accordingly.
Comments