Let us now discuss a way to use the create desk characteristic.
The SQL Expression Language constructs its expressions in opposition to table columns. SQLAlchemy Column object represents a column in a database desk that is in turn represented through a Tableobject. Metadata consists of definitions of tables and associated gadgets including index, view, triggers, and many others.
Hence an object of MetaData class from SQLAlchemy Metadata is a set of Table objects and their related schema constructs. It holds a collection of Table items as well as an optional binding to an Engine or Connection.
from sqlalchemy import MetaData meta = MetaData()
Constructor of MetaData elegance will have bind and schema parameters which are by means of default None.
Next, we define our tables all inside above metadata catalog, the usage of the Table assemble, which resembles everyday SQL CREATE TABLE announcement.
An object of Table elegance represents corresponding desk in a database. The constructor takes the subsequent parameters −
|Name||Name of the table|
|Metadata||MetaData object that will hold this table|
|Column(s)||One or more objects of column class|
Column item represents a column in a database table. Constructor takes name, kind and other parameters consisting of primary_key, autoincrement and different constraints.
SQLAlchemy matches Python facts to the great viable regularly occurring column information sorts defined in it. Some of the everyday data sorts are −
To create a students table in university 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), )
The create_all() characteristic makes use of the engine item to create all the described table objects and shops the data in metadata.
Complete code is given below for you to create a SQLite database university.Db with a students desk in it.
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) meta.create_all(engine)
Because echo attribute of create_engine() feature is about to True, the console will show the actual SQL question for table creation as follows −
CREATE TABLE students ( id INTEGER NOT NULL, name VARCHAR, lastname VARCHAR, PRIMARY KEY (id) )
The college.Db can be created in cutting-edge running directory. To take a look at if the students desk is created, you can open the database the use of any SQLite GUI tool including SQLiteStudio.
The beneath image suggests the scholars desk this is created inside the database −