Environment Setting
Here we will use PostgreSQL to demonstrate the usage of SQLAlchemy. In order to have a PostgreSQL DB for testing, you can leverage the exist docker image:
Connecting to Database
Engine class connects a Pool and Dialect together to provide a source of database connectivity and behavior. An object of Engine class is instantiated using the create_engine() function:
To specifically mention DB-API to be used for connection, the URL string takes the form as follows −
- dialect[+driver]://user:password@host/dbname
- mysql+pymysql://
: @ /
Creating Table
Let us now discuss how to use the create table function.
The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Table object. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc.
Hence an object of MetaData class from SQLAlchemy is a collection of Table objects and their associated schema constructs. It holds a collection of Table objects as well as an optional binding to an Engine or Connection.
- from sqlalchemy import MetaData
- meta = MetaData()
SQLAlchemy matches Python data to the best possible generic column data types defined in it. For more, please refer to Column and Data Types. To create a students table in college database, use the following snippet:
- from sqlalchemy import Table, Column, Integer, String, MetaData
- meta = MetaData()
- students = Table(
- 'students', meta,
- Column('id', Integer, primary_key = True),
- Column('name', String),
- Column('lastname', String),
- )
- meta.create_all(engine)
- from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
- db_string = "postgresql://postgres:
@localhost/testdb" - engine = create_engine(db_string, echo = True)
- meta = MetaData()
- students = Table(
- 'students', meta,
- Column('id', Integer, primary_key = True),
- Column('name', String),
- Column('lastname', String),
- )
- meta.create_all(engine)
- CREATE TABLE students (
- id SERIAL NOT NULL,
- name VARCHAR,
- lastname VARCHAR,
- PRIMARY KEY (id)
- )
Supplement
* PostgreSQL - CREATE Database
* PostgreSQL - CREATE Table
* docker 命令解析之`PS`
沒有留言:
張貼留言