Read data from SQL database using Python

To read data from a SQL database using Python, you can use the pyodbc library to connect to the database and execute a SQL query to select the data. Here’s a sample code

import pyodbc

# Connect to the SQL database
conn = pyodbc.connect('Driver={SQL Server};Server=server_name;Database=database_name;Trusted_Connection=yes;')

# Define the SQL query to select data from the database
sql_query = "SELECT * FROM table_name"

# Execute the SQL query and fetch the results
cursor = conn.cursor()
cursor.execute(sql_query)
rows = cursor.fetchall()

# Iterate through the rows and print the data
for row in rows:
    print(row)

# Close the database connection
conn.close()

In this example, the SQL query SELECT * FROM table_name selects all the rows from the table table_name in the SQL database. You can modify the SQL query to match the columns and table structure in your database. Once the query is executed, the fetchall() method retrieves all the rows from the cursor, and the rows can be iterated through to access the individual values.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech