SQL Expressions
SQL expressions are constructed using corresponding methods relative to target table object. For example, the INSERT statement is created by executing insert() method as follows:
It is possible to insert value in a specific field by values() method to insert object. The code for the same is given below:
The SQL echoed on Python console doesn’t show the actual value (‘john’ in this case). Instead, SQLALchemy generates a bind parameter which is visible in compiled form of the statement:
Executing Expression
In order to execute the resulting SQL expressions, we have to obtain a connection object representing an actively checked out DBAPI connection resource and then feed the expression object as shown in the code below:
- conn = engine.connect()
Following is the entire snippet that shows the execution of INSERT query using SQLAlchemy’s core technique:
- from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
- db_string = "postgresql://postgres:john7810@localhost/testdb"
- engine = create_engine(db_string, echo = True)
- meta = MetaData(bind=engine)
- students = Table('students', meta, Column('id', Integer, primary_key = True),
- Column('name', String), Column('lastname', String))
- ins = students.insert().values(name = 'Lee', lastname = 'John')
- conn = engine.connect()
- result = conn.execute(ins)
- testdb=# SELECT * FROM students;
- id | name | lastname
- ----+------+----------
- 1 | Lee | John
- (1 row)
The select() method of table object enables us to construct SELECT expression:
We can use this select object as a parameter to execute() method of connection object as shown in the code below:
The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method:
The complete code to print all rows from students table is shown below:
- demo3.py
- from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
- db_string = "postgresql://postgres:john7810@localhost/testdb"
- engine = create_engine(db_string, echo = True)
- meta = MetaData(bind=engine)
- students = Table('students', meta, Column('id', Integer, primary_key = True),
- Column('name', String), Column('lastname', String))
- conn = engine.connect()
- s = students.select()
- result = conn.execute(s)
- for row in result:
- print("id={}, name={}; lastname={}".format(row[0], row[1], row[2]))
The WHERE clause of SELECT query can be applied by using Select.where(). For example, if we want to display rows with id >2:
- s = students.select().where(students.c.id>2)
- result = conn.execute(s)
- for row in result:
- print (row)
Here, we have to note that select object can also be obtained by select() function in sqlalchemy.sql module. The select() function requires the table object as argument:
- from sqlalchemy.sql import select
- students = meta.tables['students']
- s = select([students])
- result = conn.execute(s)
Supplement
* SQLAlchemy Document - Insert, Updates, Deletes
沒有留言:
張貼留言