from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:password@localhost/db_name")
We will be using the connection variable my_conn in our scripts here.
Listing all tables of the database
r_set=my_conn.execute("SHOW TABLES");
for row in r_set:
print(row)
Listing all row of a table
r_set=my_conn.execute("SELECT * FROM student");
for row in r_set:
print(row)
Using SQLite database with SQLAlchemy
We can use SQLAlchemy to manage SQLite. The script part remain same and only the connection string changes. Here we have created the connection engine ( the variable ) my_conn. We used a common varaible my_conn as output of both connection engines so the script part remain same throughout.
from sqlalchemy import create_engine
my_conn = create_engine("sqlite:///my_db.db")
Advantage of SQLalchem
If you want to change to other database ( say SQLite ) then only connection string needs to be changed as by using SQLAlchemy can be used to connect different databases. Here the script part mostly remain same. Easy portability is the main advantages here.