Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run SQL Query in Python

I need to convert a big SQL code in python. Instead of converting SQL code to python, Is there any way we can run sql query in python Script? Let's suppose there is a stored procedure in my MsSqlServer. How can I call that stored procedure in python?

like image 355
harry Avatar asked Apr 24 '26 22:04

harry


1 Answers

A way could be the following (you could save the whole query which will of course be more complicated than the one in the example):

# Import sqlalchemy's create_engine() function
from sqlalchemy import create_engine
import pandas as pd

# Create the database engine
engine = create_engine("mssql+pyodbc://user:pass@dsn")

# Create a SQL query to load the entire table
query = """
SELECT * 
  FROM XXX;
"""

# Load with the SQL query
load = pd.read_sql(query, engine)
like image 104
Michele Giglioni Avatar answered Apr 27 '26 11:04

Michele Giglioni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!