3

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?

1

5 Answers 5

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

for that need to import pandas at the beginning: import pandas as pd. I have amended the reply above
1

There are plenty of ways to run SQL commands within a Python script. Check out SqlAlchemy.

Comments

1

You could use SQLAlchemy with the PyODBC driver, which supports Microsoft SQL Servers. You can install both packages directly from PyPi.

from sqlalchemy import create_engine
engine = create_engine("mssql+pyodbc://user:pass@dsn")
engine.execute("SELECT 1;")

Comments

1

If you are working with mysql localhost basically in XAMP then you can include below code in your python file no need to use sql statements SQLALchemy will work fine.

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/yourdatabasename'

Comments

1

in addition to other answers, using sqlalchemy (https://www.sqlalchemy.org/), it is possible to execute raw SQL, without using the "pythonic" object way to perform db actions. For example, for SQLITE (which you can use alternative drivers), you can run it this way.


# install with `pip install sqlalchemy`

import sqlalchemy as db

engine = db.create_engine('sqlite:///my-example-db.sqlite')

with engine.connect() as con:

    rs = con.execute('SELECT * FROM myexampletable')

    for row in rs:
        print(row)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.