Programming in Python V: Accessing a Database



Similar documents
Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

Unit 3. Retrieving Data from Multiple Tables

Writing MySQL Scripts With Python's DB-API Interface

Best Practices for Dynamic SQL

Writing MySQL Scripts with Python DB-API

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Python. Data bases. Marcin Młotkowski. 8th May, 2013

Database Fundamentals

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Oracle Database: SQL and PL/SQL Fundamentals

Automating SQL Injection Exploits

Server-Side JavaScript Injection Bryan Sullivan, Senior Security Researcher, Adobe Secure Software Engineering Team July 2011

Oracle 10g PL/SQL Training

This presentation explains how to monitor memory consumption of DataStage processes during run time.

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

ANDROID APPS DEVELOPMENT FOR MOBILE GAME

Oracle Database: SQL and PL/SQL Fundamentals

Maintaining Stored Procedures in Database Application

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

The Import & Export of Data from a Database

Oracle SQL. Course Summary. Duration. Objectives

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

External Network & Web Application Assessment. For The XXX Group LLC October 2012

Introduction to Python

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey

Database Security. Principle of Least Privilege. DBMS Security. IT420: Database Management and Organization. Database Security.

Cyber Security Challenge Australia 2014

Microsoft SQL Server Scheduling

How to Improve Database Connectivity With the Data Tools Platform. John Graham (Sybase Data Tooling) Brian Payton (IBM Information Management)

Beginning to Program Python

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Webapps Vulnerability Report

Short notes on webpage programming languages

Information Systems SQL. Nikolaj Popov

dbext for Vim David Fishburn h5p://

Microsoft Windows PowerShell v2 For Administrators

Oracle Database 12c: Introduction to SQL Ed 1.1

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Database programming made easier Master thesis of Roland Balk

Database Security. Sarajane Marques Peres, Ph.D. University of São Paulo

Python programming databasing

Real SQL Programming 1

Web Application Security Considerations

CS 145: NoSQL Activity Stanford University, Fall 2015 A Quick Introdution to Redis

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

SQL Injection. SQL Injection. CSCI 4971 Secure Software Principles. Rensselaer Polytechnic Institute. Spring

SQL injection: Not only AND 1=1. The OWASP Foundation. Bernardo Damele A. G. Penetration Tester Portcullis Computer Security Ltd

Other Language Types CMSC 330: Organization of Programming Languages

SQL Server Database Coding Standards and Guidelines

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

College Tuition: Data mining and analysis

COURSE OUTLINE UCLA EXTENSI ON MGMNT X

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

CS346: Database Programming.

Report Generator in ix Developer 2.0 KI00319A

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Oracle Database 11g: SQL Tuning Workshop Release 2

What's New in ADP Reporting?

Joomla! Override Plugin

Databases 2011 The Relational Model and SQL

How to Copy A SQL Database SQL Server Express (Making a History Company)

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Enhanced Model of SQL Injection Detecting and Prevention

A database can simply be defined as a structured set of data

Ad Hoc Advanced Table of Contents

Computer Security: Principles and Practice

Search help. More on Office.com: images templates

SPV Reporting Tool VBA Code User Guide. Last Updated: December, 2009

Threat Modeling. Categorizing the nature and severity of system vulnerabilities. John B. Dickson, CISSP

March Module 3 Processing MOVES Output

Utilizing SFTP within SSIS

Using Temporary Tables to Improve Performance for SQL Data Services

ADP Workforce Now V3.0

Oracle For Beginners Page : 1

Query-by-Example (QBE)

Oracle Database 11g: SQL Tuning Workshop

A Brief Introduction to MySQL

How to Create Dashboards. Published

Using ODBC and other database interfaces

Using Python, Django and MySQL in a Database Course

Introduction to Databases and Data Mining

Darshan Institute of Engineering & Technology PL_SQL

Generating XML from Relational Tables using ORACLE. by Selim Mimaroglu Supervisor: Betty O NeilO

Object Relational Mapping for Database Integration

Relational Database Basics Review

Using SQL Server Management Studio

APEX_ITEM and Dynamic Tabular Forms

Database Programming with PL/SQL: Learning Objectives

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

ASP.NET Programming with C# and SQL Server

Transcription:

Programming in Python V: Accessing a Database Computer Science 105 Boston University David G. Sullivan, Ph.D. Accessing a Database from Python Import the necessary Python module: import sqlite3 Connect to the database and create an object known as a database handle, assigning it to a variable named db. db = sqlite3.connect('<name of database file>') To connect to the database that we used for PS 2 and 3: put the database file (movie.db) in the same folder as the Python program that will access it use the following command in the program: db = sqlite3.connect('movie.db')

Performing a Query Given a database handle, we can perform a query by: using the database handle to create a cursor object: cursor = db.cursor() using the cursor to execute the query: cursor.execute("<select command>") Once the query has been executed, we use the cursor to access the results. To get one tuple from the result, we use the fetchone function: row = cursor.fetchone() if there's nothing to get, this function returns None Performing a Query (cont.) Example for our movie database: >>> cursor = db.cursor() >>> cursor.execute("select name, year FROM Movie;") >>> cursor.fetchone() ('Avatar', 2009)

Performing a Query (cont.) Another example: >>> cursor.execute('''select name, rating FROM Movie WHERE year = 1976;''') >>> cursor.fetchone() ('Rocky', 'PG') >>> cursor.fetchone() ('Network', 'R') >>> cursor.fetchone() ("All the President's Men", 'PG') Using a for Loop to Display Query Results Python allows us to use a for loop to process the results of a query one tuple at a time. Syntax: # code to process tuple goes here Example: cursor = db.cursor() cursor.execute('''select name, rating FROM Movie WHERE year = 1976;''') The above code would give the following output: Rocky PG Network R All the President's Men PG

Executing a Query Based on User Input How can we execute a query that's based on user inputs? example interaction: year to search for? 1976 Rocky PG Network R All the President's Men PG In theory, we could construct the query using string concatenation: searchyear = input("year to search for? ") command = '''SELECT name, rating FROM Movie WHERE year = ''' command = command + searchyear + ";" cursor.execute(command) SQL Injection Vulnerability Problem: constructing a query using string concatenation can lead to a serious security breaches. known as a SQL injection. Example: let's say that in addition to the movie tables, there's a table called Secret containing sensitive data. The user of the program shown on the previous slide can see data from Secret by entering something like this: Year to search for? 1976; SELECT * FROM Secret The string concatenation will produce the following: SELECT name, rating FROM Movie WHERE year = 1976; SELECT * FROM Secret; The program will display the entire first two columns of Secret!

SQL Injection Vulnerability (cont.) Here's another problematic input! Year to search for? 1976; DROP TABLE Secret Parameterized Queries To avoid SQL injections, we use a parameterized query. example: command = '''SELECT name, rating FROM Movie WHERE year =?;'''? is a placeholder We execute the parameterized query as follows: cursor.execute(command, [searchyear]) command string with placeholders a list containing the values that should replace the placeholders (the parameters) The execute function replaces the placeholders with the specified values taking whatever steps are needed to treat each parameter as a single literal value.

Parameterized Queries (cont.) Here's a query that takes three parameters: command = '''SELECT M.name, M.year FROM Movie M, Person P, Director D WHERE M.id = D.movie_id AND P.id = D.director_id AND P.name =? AND M.year BETWEEN? AND?;''' Here's an example of using it: dirname = input("director's name: ") start = input("start of year range: ") end = input("end of year range: ") cursor.execute(command, [dirname, start, end]) The Full Program (getmoviesbydirector.py) import sqlite3 filename = input("name of database file: ") db = sqlite3.connect(filename) cursor = db.cursor() dirname = input("director's name: ") start = input("start of year range: ") end = input("end of year range: ") command = '''SELECT M.name, M.year FROM Movie M, Person P, Director D WHERE M.id = D.movie_id AND P.id = D.director_id AND P.name =? AND M.year BETWEEN? AND?;''' cursor.execute(command, [dirname, start, end])

Handling Queries with No Results What if the user enters a director who isn't in the database, or a range of years with no movies for the director? We'd like our program to print a message when this happens. One way of doing this is to maintain a count of the number of tuples that the program processes:... cursor.execute(command, [dirname, start, end]) count = 0 count = count + 1 # print a message if there were no results # what should go here? Concluding a Database Session At the end of a program that accesses a database, you should always do the following: commit the transaction in which the commands were executed: db.commit() close the database handle: db.close()

A Front-End for Our Movie Database Let's write a Python program that serves as a front-end to our movie database. For now, it will do the following: get the name of a person from the user use a parameterized SELECT command to retrieve the appropriate record from the Person table if the specified person is in the database, print his/her information in the following format: <name> was born on <dob> in <pob>. otherwise, print an appropriate error message Extension: change the format of the dob from yyyy-mm-dd to mm/dd/yyyy A Front-End for Our Movie Database

Converting the Date Format To change the format of the dob from yyyy-mm-dd to mm/dd/yyyy, what should we do?