In the previous bankruptcy, we've got mentioned about expression Language in SQLAlchemy. Now allow us to continue toward the steps involved in connecting to a database.
Engine class connects a Pool and Dialect together to offer a supply of database connectivity and behavior. An object of Engine elegance is instantiated the use of the create_engine() function.
The create_engine() function takes the database as one argument. The database isn't had to be defined anywhere. The standard calling shape has to ship the URL because the first positional argument, usually a string that indicates database dialect and connection arguments. Using the code given under, we can create a database.
>>> from sqlalchemy import create_engine >>> engine = create_engine('sqlite:///college.db', echo = True)
For a MySQL database, use the beneath command −
engine = create_engine("mysql://user:pwd@localhost/college",echo = True)
To in particular mention DB-API to be used for connection, the URL string takes the shape as follows −
For instance, in case you are the usage of PyMySQL motive force with MySQL, use the following command −
The echo flag is a shortcut to installation SQLAlchemy logging, which is executed via Python’s standard logging module. In the following chapters, we can learn all of the generated SQLs. To cover the verbose output, set echo attribute to None. Other arguments to create_engine() characteristic may be dialect unique.
The create_engine() feature returns an Engine object. Some vital methods of Engine class are −
|Sr.No.||Method & Description|
Returns connection object
Executes a SQL statement construct
Returns a context manager delivering a Connection with a Transaction established. Upon successful operation, the Transaction is committed, else it is rolled back
Disposes of the connection pool used by the Engine
Driver name of the Dialect in use by the Engine
Returns a list of all table names available in the database
Executes the given function within a transaction boundary