Questions tagged [sqlalchemy]

SQLAlchemy is a Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

NOTE: PLEASE report bugs / advanced issues as a GitHub discussion or on the sqlalchemy mailing list - much more comprehensive help for complex issues is available there. Please follow these guidelines when posting.

Example

metadata = MetaData()
engine = sqlalchemy.create_engine('mysql://user:pass@localhost/sql_db') # session handler

names = Table('names', metadata,
  Column('id', Integer),
  Column('name', String(60))
)

metadata.create_all(engine) # create tables in case they do not exist

# ask user for id and name
_id = int(input('indicate id: '))  # use `_id`, as `id` is a reserved word in python
name = input('indicate name: ')

ins = names.insert().values(name=name, id=_id) # insert values in table

References

Books:

Talks:

22992 questions
89
votes
4 answers

SQLAlchemy insert or update example

In Python, using SQLAlchemy, I want to insert or update a row. I tried this: existing = db.session.query(Toner) for row in data: new = Toner(row[0], row[1], row[2]) It does not work. How do I INSERT or UPDATE new into Toner table? I suspect…
Andrii Yurchuk
  • 3,090
  • 6
  • 29
  • 40
89
votes
2 answers

Sqlalchemy - Difference between query and query.all in for loops

I would like to ask whats the difference between for row in session.Query(Model1): pass and for row in session.Query(Model1).all(): pass is the first somehow an iterator bombarding your DB with single queries and the latter "eager" queries…
Tom
  • 3,115
  • 6
  • 33
  • 38
88
votes
2 answers

SQLAlchemy multiple foreign keys in one mapped class to the same primary key

Am trying to setup a postgresql table that has two foreign keys that point to the same primary key in another table. When I run the script I get the error sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between…
lukik
  • 3,919
  • 6
  • 46
  • 89
88
votes
4 answers

Getting first row from sqlalchemy

I have the following query: profiles = session.query(profile.name).filter(and_(profile.email == email, profile.password == password_hash)) How do I check if there is a row and how do I just return the first (should only be one if there is a match)?
Asken
  • 7,679
  • 10
  • 45
  • 77
88
votes
4 answers

How can I do multiple "order_by" in Flask-SQLAlchemy?

Let's say I have a User model with fields popularity and date_created. I want to do the following query: SELECT * FROM user ORDER BY popularity DESC, date_created DESC LIMIT 10 In SQLAlchemy, for a single one this…
Noé Malzieu
  • 2,530
  • 3
  • 22
  • 27
88
votes
3 answers

Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly?

Why is this simple test case inserting 100,000 rows 25 times slower with SQLAlchemy than it is using the sqlite3 driver directly? I have seen similar slowdowns in real-world applications. Am I doing something wrong? #!/usr/bin/env python # Why is…
braddock
  • 1,345
  • 2
  • 11
  • 13
87
votes
5 answers

How to delete a table in SQLAlchemy?

I want to delete a table using SQLAlchemy. Since I am testing over and over again, I want to delete the table my_users so that I can start from scratch every single time. So far I am using SQLAlchemy to execute raw SQL through the engine.execute()…
fedorqui
  • 275,237
  • 103
  • 548
  • 598
85
votes
7 answers

SQL Alchemy ORM returning a single column, how to avoid common post processing

I'm using SQL Alchemy's ORM and I find when I return a single column I get the results like so: [(result,), (result_2,)] # etc... With a set like this I find that I have to do this often: results = [r[0] for r in results] # So that I just have a…
Derek Litz
  • 10,529
  • 7
  • 43
  • 53
85
votes
3 answers

How to perform a left join in SQLALchemy?

I have a SQL query which perfroms a series of left joins on a few tables: SELECT FROM table1 t1 INNER JOIN table2 t2 ON attr = 1 AND attr2 = 1 LEFT JOIN table3 t3 ON t1.Code = t2.Code AND t3.Date_ = t1.Date_ LEFT JOIN…
user1742188
  • 4,563
  • 8
  • 35
  • 60
85
votes
6 answers

AttributeError while querying: Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute

The following code: Base = declarative_base() engine = create_engine(r"sqlite:///" + r"d:\foo.db", listeners=[ForeignKeysListener()]) Session = sessionmaker(bind = engine) ses = Session() class Foo(Base): __tablename__ =…
Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74
84
votes
7 answers

sqlalchemy exists for query

How do I check whether data in a query exists? For example: users_query = User.query.filter_by(email='x@x.com') How I can check whether users with that email exist? I can check this with users_query.count() but how to check it with exists?
lestat
  • 1,565
  • 2
  • 14
  • 12
82
votes
12 answers

python pandas to_sql with sqlalchemy : how to speed up exporting to MS SQL?

I have a dataframe with ca 155,000 rows and 12 columns. If I export it to csv with dataframe.to_csv , the output is an 11MB file (which is produced instantly). If, however, I export to a Microsoft SQL Server with the to_sql method, it takes between…
Pythonista anonymous
  • 8,140
  • 20
  • 70
  • 112
82
votes
5 answers

Could not assemble any primary key columns for mapped table

When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong? $ python app.py db upgrade [skipped] sqlalchemy.exc.ArgumentError: Mapper…
Michael Samoylov
  • 2,933
  • 3
  • 25
  • 33
81
votes
4 answers

SQLAlchemy + SQL Injection

What are the best practices for mitigating SQL injection attacks when using SQLAlchemy?
Mike
  • 58,961
  • 76
  • 175
  • 221
81
votes
4 answers

Alembic: IntegrityError: "column contains null values" when adding non-nullable column

I'm adding a column to an existing table. This new column is nullable=False. op.add_column('mytable', sa.Column('mycolumn', sa.String(), nullable=False)) When I run the migration, it complains: sqlalchemy.exc.IntegrityError: column "mycolumn"…
Ron
  • 7,588
  • 11
  • 38
  • 42