Pandas to open a SQL database or to run a SQL query against a database
There is more than one way to do this depending on the type of SQL database you are working with: the sqlite3 library or the sqlalchemy library.
In the same folder as this Jupyter notebook, there is a SQLite database file called "population_data.db". SQLite is a database engine meant for single applications. The entire database is contained in one file. You can read more about SQLite here.
Sqlite is a database storage engine, which can be better compared with things such as MySQL, PostgreSQL, Oracle, MSSQL, etc. It is used to store and retrieve structured data from files.
SQLAlchemy is a Python library that provides an object relational mapper (ORM). It does what it suggests: it maps your databases (tables, etc.) to Python objects, so that you can more easily and natively interact with them. SQLAlchemy can be used with sqlite, MySQL, PostgreSQL, etc.
So, an ORM provides a set of tools that let you interact with your database models consistently across database engines.
SQLAlchemy is a powerful database access tool kit for Python, with its object-relational mapper (ORM) being one of its most famous components, and the one discussed and used here.
When you’re working in an object-oriented language like Python, it’s often useful to think in terms of objects. It’s possible to map the results returned by SQL queries to objects, but doing so works against the grain of how the database works. Sticking with the scalar results provided by SQL works against the grain of how Python developers work. This problem is known as object-relational impedance mismatch.
The ORM provided by SQLAlchemy sits between the SQLite database and your Python program and transforms the data flow between the database engine and Python objects. SQLAlchemy allows you to think in terms of objects and still retain the powerful features of a database engine
These two things are not mutually exclusive, because they aren't the same type of thing.
SQLite3 is a database engine, in other words it's the actual implementation of a database. It provides an abstraction over the messy details of how to store and access raw data on your filesystem.
SQLAlchemy is an Object-Relational Mapper, a thing that lets you use object-oriented Python (in this case*) code to represent your data, and abstracts away the fiddly parts of translating from code to the SQL used to communicate with the database engine, and vice versa.
The two are on separate layers: at the bottom you have SQLite, then on top of that you have SQLAlchemy, then you have your regular application code.
* other ORMs include ActiveRecord for Ruby or Doctrine for PHP, for example
Comments
Post a Comment