INTRODUCTION TO DATABASES IN PYTHON. Creating Databases and Tables

Similar documents
PART I SQLAlchemy Core

This tutorial is designed for all those Python programmers who would like to understand the ORM framework with SQLAlchemy and its API.

Draft. Students Table. FName LName StudentID College Year. Justin Ennen Science Senior. Dan Bass Management Junior

origin destination duration New York London 415 Shanghai Paris 760 Istanbul Tokyo 700 New York Paris 435 Moscow Paris 245 Lima New York 455

Unit 1 - Chapter 4,5

Essential SQLAlchemy. An Overview of SQLAlchemy. Rick Copeland Author, Essential SQLAlchemy Predictix, LLC

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Update Table Schema Sql Server 2008 Add Column Default Value

user specifies what is wanted, not how to find it

alchimia Documentation

IMPORTING DATA IN PYTHON I. Introduction to relational databases

Canvas Data Utilities Documentation

Basic SQL. Basic SQL. Basic SQL

INTRODUCTION TO DATABASES IN PYTHON. Filtering and Targeting Data

CS 250 SQL and SQLite. Benjamin Dicken

Database Systems CSE 303. Outline. Lecture 06: SQL. What is Sub-query? Sub-query in WHERE clause Subquery

Text Input and Conditionals

CSCE 548 Building Secure Software SQL Injection Attack

A1 (Part 2): Injection SQL Injection

Query To Find Table Name Using Column Name In Sql Server

SQL Structured Query Language Introduction

SQL 2 (The SQL Sequel)

Dobby Documentation. Release 0.1. Antoine Bertin

SQL Data Definition Language

Lecture 7 Stored procedure

Database Technology. Topic 6: Triggers and Stored Procedures

CSC Web Programming. Introduction to SQL

CS2300: File Structures and Introduction to Database Systems

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

L6 Application Programming. Thibault Sellam Fall 2018

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

ITP 342 Advanced Mobile App Dev. Core Data

CGS 3066: Spring 2017 SQL Reference

DATABASE SECURITY AND PRIVACY. Some slides were taken from Database Access Control Tutorial, Lars Olson, UIUC CS463, Computer Security

MySQL: Querying and Using Form Data

COSC344 Database Theory and Applications. Lecture 11 Triggers

Understanding Advanced Blind SQLI attack

Relational Database Management System 2014

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

1) Introduction to SQL

Advanced SQL GROUP BY Clause and Aggregate Functions Pg 1

First name (printed): a. DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Homework notes. Homework 2 grades posted on canvas. Homework 3 due tomorrow. Homework 4 posted on canvas. Due Tuesday, Oct. 3

An Introduction to Python

Querying Data with Transact SQL

ACCESS isn t only a great development tool it s

Using DbVisualizer Variables

Introduction to SQL Server. nikos bikakis

Programming in Python 3

Problem Solving for Intro to Computer Science

Introduction to Bioinformatics

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

agate-sql Documentation

Structure Query Language (SQL)

Overview of MySQL Structure and Syntax [2]

An Introduction to Structured Query Language

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Slides by: Ms. Shree Jaswal

Sql Cannot Create Index On View Not Schema Bound

Chapter-14 SQL COMMANDS

SQL stands for Structured Query Language. SQL lets you access and manipulate databases

Spatial Databases by Open Standards and Software 3.

Copy Data From One Schema To Another In Sql Developer

Database. Ed Milne. Theme An introduction to databases Using the Base component of LibreOffice

Database Programming with PL/SQL

SQLAlchemy-Searchable Documentation

INTRODUCTION TO JDBC - Revised spring

Chapter 7 PHP Files & MySQL Databases

Variables, Constants, and Data Types

Play with Python: An intro to Data Science

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Get Table Schema In Sql Server 2005 Modify. Column Size >>>CLICK HERE<<<

Mysql Create Table With Multiple Index Example

CIS 45, The Introduction. What is a database? What is data? What is information?

Limit Rows Selected. Copyright 2008, Oracle. All rights reserved.

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

DATABASE DESIGN - 1DL400

STOP DROWNING IN DATA. START MAKING SENSE! An Introduction To SQLite Databases. (Data for this tutorial at

Oracle 11g Table Name Length Limit

SQL-Server. learn SQL and operations in ms sql server 2008, ms sql server 2012, ms sql server 2014, ms sql server 2016

SQL Retrieving Data from Multiple Tables

Excel VBA Variables, Data Types & Constant

Hints: I used a left fold and wrote a named helper function when I created my solution.

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

HIBERNATE - INTERCEPTORS

CS 338 Nested SQL Queries

This lecture. Databases - JDBC I. Application Programs. Database Access End Users

SQL Commands & Mongo DB New Syllabus

Mysql Insert Manual Timestamp Into Datetime Field

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

Landscape Gardening AQA GCSE Computer Science Controlled Assessment

SQL functions fit into two broad categories: Data definition language Data manipulation language

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Table of Contents. Table of Contents

Transcription:

INTRODUCTION TO DATABASES IN PYTHON Creating Databases and Tables

Creating Databases Varies by the database type Databases like PostgreSQL and MySQL have command line tools to initialize the database With SQLite, the create_engine() statement will create the database and file is they do not already exist

Building a Table In [1]: from sqlalchemy import (Table, Column, String,...: Integer, Decimal, Boolean) In [2]: employees = Table('employees', metadata,...: Column('id', Integer()),...: Column('name', String(255)),...: Column('salary', Decimal()),...: Column('active', Boolean())) In [3]: metadata.create_all(engine) In [4]: engine.table_names() Out[4]: [u'employees']

Creating Tables Still uses the Table object like we did for reflection Replaces the autoload keyword arguments with Column objects Creates the tables in the actual database by using the create_all() method on the MetaData instance You need to use other tools to handle database table updates, such as Alembic or raw SQL

Creating Tables - Additional Column Options unique forces all values for the data in a column to be unique nullable determines if a column can be empty in a row default sets a default value if one isn t supplied.

Building a Table with Additional Options In [1]: employees = Table('employees', metadata,...: Column('id', Integer()),...: Column('name', String(255), unique=true,...: nullable=false),...: Column('salary', Float(), default=100.00),...: Column('active', Boolean(), default=true)) In [2]: employees.constraints Out[2]: {CheckConstraint(... Column('name', String(length=255), table=<employees>, nullable=false), Column('salary', Float(), table=<employees>, default=columndefault(100.0)), Column('active', Boolean(), table=<employees>, default=columndefault(true))... UniqueConstraint(Column('name', String(length=255), table=<employees>, nullable=false))}

INTRODUCTION TO DATABASES IN PYTHON Let s practice!

INTRODUCTION TO DATABASES IN PYTHON Inserting Data into a Table

Adding Data to a Table Done with the insert() statement Insert() takes the table we are loading data into as the argument We add all the values we want to insert in with the values clause as column=value pairs Doesn t return any rows, so no need for a fetch method

Inserting One Row In [1]: from sqlalchemy import insert In [2]: stmt = insert(employees).values(id=1, name='jason', salary=1.00, active=true) In [3]: result_proxy = connection.execute(stmt) In [4]: print(result_proxy.rowcount) Out[4]: 1

Inserting Multiple Rows Build an insert statement without any values Build a list of dictionaries that represent all the values clauses for the rows you want to insert Pass both the stmt and the values list to the execute method on connection

Inserting Multiple Rows In [1]: stmt = insert(employees) In [2]: values_list = [ {'id': 2, 'name': 'Rebecca', 'salary': 2.00, 'active': True}, {'id': 3, 'name': 'Bob', 'salary': 0.00, 'active': False} ] In [3]: result_proxy = connection.execute(stmt, values_list) In [4]: print(result_proxy.rowcount) Out[4]: 2

INTRODUCTION TO DATABASES IN PYTHON Let s practice!

INTRODUCTION TO DATABASES IN PYTHON Updating Data in a Table

Updating Data in a Table Done with the update statement Similar to the insert statement but includes a where clause to determine what record will be updated We add all the values we want to update with the values clause as column=value pairs

Updating One Row In [1]: from sqlalchemy import update In [2]: stmt = update(employees) In [3]: stmt = stmt.where(employees.columns.id == 3) In [4]: stmt = stmt.values(active=true) In [5]: result_proxy = connection.execute(stmt) In [6]: print(result_proxy.rowcount) Out[6]: 1

Updating Multiple Rows Build a where clause that will select all the records you want to update

Inserting Multiple Rows In [1]: stmt = update(employees) In [2]: stmt = stmt.where( ) employees.columns.active == True In [3]: stmt = stmt.values(active=false, salary=0.00) In [4]: result_proxy = connection.execute(stmt) In [5]: print(result_proxy.rowcount) Out[5]: 3

Correlated Updates In [1]: new_salary = select([employees.columns.salary]) In [2]: new_salary = new_salary.order_by(desc(...: employees.columns.salary) ) In [3]: new_salary = new_salary.limit(1) In [4]: stmt = update(employees) In [5]: stmt = stmt.values(salary=new_salary) In [6]: result_proxy = connection.execute(stmt) In [7]: print(result_proxy.rowcount) Out[7]: 3

Correlated Updates Uses a select() statement to find the value for the column we are updating Commonly used to update records to a maximum value or change a string to match an abbreviation from another table

INTRODUCTION TO DATABASES IN PYTHON Let s practice!

Deleting Data from a Database

Deleting Data from a Table Done with the delete() statement delete() takes the table we are loading data into as the argument A where() clause is used to choose which rows to delete Hard to undo so BE CAREFUL!!!

Deleting all Data from a Table In [1]: from sqlalchemy import delete In [2]: stmt = select([ func.count(extra_employees.columns.id)]) In [3]: connection.execute(stmt).scalar() Out[3]: 3 In [4]: delete_stmt = delete(extra_employees) In [5]: result_proxy = connection.execute(delete_stmt) In [6]: result_proxy.rowcount Out[6]: 3

Deleting Specific Rows Build a where clause that will select all the records you want to delete

Deleting Specific Rows In [1]: stmt = delete(employees).where( employees.columns.id == 3) In [2]: result_proxy = connection.execute(stmt) In [3]: result_proxy.rowcount Out[3]: 1

Dropping a Table Completely Uses the drop method on the table Accepts the engine as an argument so it knows where to remove the table from Won t remove it from metadata until the python process is restarted

Dropping a table In [1]: extra_employees.drop(engine) In [2]: print(extra_employees.exists(engine)) Out[2]: False

Dropping all the Tables Uses the drop_all() method on MetaData

Dropping all the Tables In [1]: metadata.drop_all(engine) In [2]: engine.table_names() Out[2]: []

INTRODUCTION TO DATABASES IN PYTHON Let s practice!