It's pretty easy to insert data into a database by using sqlalchemy.
address.name = 'Joe'
address.age = 26
session.add(address)
But actually I have three tables - how can I specify the table I want to insert my data in?
It's pretty easy to insert data into a database by using sqlalchemy.
address.name = 'Joe'
address.age = 26
session.add(address)
But actually I have three tables - how can I specify the table I want to insert my data in?
I solved the problem by using the sql expression language to add the new row:
engine.execute(table_addresses.insert(), name='Joe', age=20)
engine.execute(table_contacts.insert(), email='[email protected]', cellnumber='267534320')
Normaly I use the ORM but in my case it is more convinient.
session.execute(table_addresses.insert().values(name='Joe', age=20)) instead.engine.execute work ?You will probably want to look at the sqlalchemy ORM tutorial.
To get you started though, I suspect you are going to want to set up something like the following.
from sqlalchemy import Column, Integer, String
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
def __init__(self, name, age):
self.name = name
self.age = age
Now since it appears you already know how to get a session, you could just do this
address = Address('Joe', 26)
session.add(address)
session.commit() # This will do the actual database insertion
Although it is possible that you could probably just try to do it on the fly, it probably wouldn't make your life easier, as you'd still have to tell it what objects relate to integers, strings, etc, to map to the database table.
__tablename__ = 'addresses' you specify the table name addresses. Are you instead rather dealing with a few identical tables that have different names?__tablename__ will be used to tell it the actual table in the database to match to. For example, based on your contacts example, you'd probably replace the class line with something like class Contact(Base): and the __tablename__ line with __tablename__ = 'contacts'. Are you instead trying to fire them into different tables dynamically on the fly?