user3462649
user3462649

Reputation: 1677

How to get cursor in SQLAlchemy

I am newbie in Python Flask. In my project we are creating db object using below code.

    app = Flask(__name__)  
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'  
    db = SQLAlchemy(app)   

I want to get cursor object from db. Can someone please help me on it. I know using connection object we can get cursor. But can we get cursor from db object which is created by above way? Thanks.

Upvotes: 33

Views: 75805

Answers (4)

abdelrahman
abdelrahman

Reputation: 76

create cursor from sqlalchemy orm session

  1. from sqlalchemy.orm import sessionmaker
  2. engine=create_engine(url)
  3. session=sessionmaker(bind= engine)()
  4. curs=session.connection().connection.cursor()

Upvotes: 5

Sucas Venior
Sucas Venior

Reputation: 301

It's ok in this way.

db = SQLAlchemy(app)
session = db.session()
cursor = session.execute(sql).cursor

Upvotes: 15

user3462649
user3462649

Reputation: 1677

Finally got answer from Flask documentation, we can get cursor from db object using,

from sqlalchemy import create_engine
engine = create_engine('your_connection_string')
connection = engine.raw_connection()
cursor = connection.cursor()

Upvotes: 70

Mangohero1
Mangohero1

Reputation: 1912

You don't have a cursor in Flask SQLAlchemy because it's an ORM. Methods exist to perform actions on the database directly, unlike packages like SQLite. Check the documentation for more info on these.

To execute SQL queries directly, you'd have to run them through the terminal directly through whichever RDBMS you're using (MySQL, PostgreSQL, etc.)

Upvotes: -6

Related Questions