{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Create A Database\n", "\n", "For this tutorial, we'll use the [SQLAlchemy](http://www.sqlalchemy.org/) Python library to communicate with a database.\n", "\n", "Let's import it:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import sqlalchemy as sa" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SQLAlchemy uses an \"engine\" object to interact with a database.\n", "\n", "To create an engine, we first need to choose a Database Management System (DBMS). We'll use [SQLite](https://sqlite.org/index.html) as our DBMS.\n", "\n", "Next, we have to define a connection URL. The URL tells SQLAlchemy which DBMS we have chosen and how to connect to our database.\n", "\n", "SQLite uses a single file for each database and the structure of the URL we need for SQLAlchemy is:\n", "\n", "```\n", "sqlite:///\n", "```\n", "\n", "Our example database will contain data about High Altitude Balloon flights. Let's name our database file ```flight.db``` and create an engine object for it:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "engine = sa.create_engine('sqlite:///flight.db')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now connect to our database using the ```connect()``` method of our engine.\n", "\n", "SQLAlchemy will look for the file we specified in our URL and establish a connection to our database. If the file doesn't exist, sqlalchemy will create it and then make the connection." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "connection = engine.connect()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should now be able to see a new 'flight.db' file in the same directory as this notebook.\n", "\n", "If you opted to [run the code on your own computer](http://owencampbell.me.uk/pages/howto#howto-local) and also installed the graphical tool, you can also now start that program and open your new 'flight.db' file." ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:sql_python_tutorial]", "language": "python", "name": "conda-env-sql_python_tutorial-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }