CS108 Lecture 19: The Python DBAPI

Similar documents
CS108 Lecture 18: Databases and SQL

Databases in Python. MySQL, SQLite. Accessing persistent storage (Relational databases) from Python code

Python and Databases

POSTGRESQL - PYTHON INTERFACE

Python and SQLite. COMP Lecture 25 March 26th, 2012 Mathieu Perreault. Monday, 26 March, 12

L6 Application Programming. Thibault Sellam Fall 2018

CMSC201 Computer Science I for Majors

LABORATORY OF DATA SCIENCE. Data Access: Relational Data Bases. Data Science and Business Informatics Degree

LECTURE 21. Database Interfaces

CSE 115. Introduction to Computer Science I

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Administrivia. Administrivia. Faloutsos/Pavlo CMU /615

Traffic violations revisited

Database Application Development

Databases. Course October 23, 2018 Carsten Witt

Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL

CS 200. Lecture 06. Database Introduction. Database Introduction. CS 200 Winter 2018

15-388/688 - Practical Data Science: Relational Data. J. Zico Kolter Carnegie Mellon University Spring 2018

Ceng 111 Fall 2015 Week 8a

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

Lecture #12: Quick: Exceptions and SQL

CS 564: DATABASE MANAGEMENT SYSTEMS. Spring 2018

Introduction to pysqlite

Kaivos User Guide Getting a database account 2

CS 200. Lecture 09 FileMaker vs SQL & Reports. FileMaker vs SQL + Reports. CS 200 Spring 2018

CS W Introduction to Databases Spring Computer Science Department Columbia University

CSE 544 Principles of Database Management Systems

Announcements. PS 3 is out (see the usual place on the course web) Be sure to read my notes carefully Also read. Take a break around 10:15am

Access Intermediate

Web Traffic - pct of Page Views

Application vulnerabilities and defences

Lecture 12. Lists (& Sequences)

Outline. CS 235: Introduction to Databases. DB Application Programming. Interface Solutions. Basic PSM Form. Persistent Stored Modules

Declarative Programming

LABORATORY OF DATA SCIENCE. Data Access: Relational Data Bases. Data Science and Business Informatics Degree

Full file at Chapter 2: An Introduction to SQL

SQL STORED ROUTINES. CS121: Relational Databases Fall 2017 Lecture 9

Announcements. Subqueries. Lecture Goals. 1. Subqueries in SELECT. Database Systems CSE 414. HW1 is due today 11pm. WQ1 is due tomorrow 11pm

CSC 261/461 Database Systems Lecture 20. Spring 2017 MW 3:25 pm 4:40 pm January 18 May 3 Dewey 1101

Performing Matrix Operations on the TI-83/84

MUTABLE LISTS AND DICTIONARIES 4

Python - Variable Types. John R. Woodward

WEB SECURITY: SQL INJECTION

JAVA AND DATABASES. Summer 2018

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

Iteration and For Loops

Lecture-14 Lookup Functions

Transactions Processing (i)

CMPT 354 Views and Indexes. Spring 2012 Instructor: Hassan Khosravi

Operating systems fundamentals - B07

INTRODUCTION TO DATA SCIENCE

Schedule. Today: Feb. 21 (TH) Feb. 28 (TH) Feb. 26 (T) Mar. 5 (T) Read Sections , Project Part 6 due.

Exceptions & a Taste of Declarative Programming in SQL

Spring 2018 Discussion 10: April 18, Introduction. 2 Creating Tables

Announcements. Multi-column Keys. Multi-column Keys (3) Multi-column Keys. Multi-column Keys (2) Introduction to Data Management CSE 414

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

Using Relational Databases for Digital Research

CS108 Lecture 16: User Defined Classes. Overview/Questions

Instructor: Craig Duckett. Lecture 11: Thursday, May 3 th, Set Operations, Subqueries, Views

Announcements. Multi-column Keys. Multi-column Keys. Multi-column Keys (3) Multi-column Keys (2) Introduction to Data Management CSE 414

CS 2316 Exam 4 Fall 2011

Informatics 1: Data & Analysis

Database Systems CSE 414

Level 3 Computing Year 2 Lecturer: Phil Smith

CS1 Lecture 3 Jan. 18, 2019

Announcements. Two Classes of Database Applications. Class Overview. NoSQL Motivation. RDBMS Review: Serverless

10/18/2017. Announcements. NoSQL Motivation. NoSQL. Serverless Architecture. What is the Problem? Database Systems CSE 414

CS317 File and Database Systems

Lecture 2: Introduction to SQL

Relational Databases

CSCD43: Database Systems Technology. Lecture 4

SQL-Server. Insert query in SQL Server. In SQL Server (Transact-SQL), the INSERT statement is used to

CSE 344 JANUARY 5 TH INTRO TO THE RELATIONAL DATABASE

SQL: Programming. Introduction to Databases CompSci 316 Fall 2017

CSC326 Persistent Programming i. CSC326 Persistent Programming

Access Intermediate

This lab will introduce you to MySQL. Begin by logging into the class web server via SSH Secure Shell Client

Iterators & Generators

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 2: Relations and SQL. September 5, Lecturer: Rasmus Pagh

CS2300: File Structures and Introduction to Database Systems

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

CS 245: Principles of Data-Intensive Systems. Instructor: Matei Zaharia cs245.stanford.edu

Introduction to SQL Part 1 By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Today's Party. Example Database. Faloutsos/Pavlo CMU /615

PTable Documentation. Release latest

CS50 Quiz Review. November 13, 2017

Advanced Programming Techniques. Database Systems. Christopher Moretti

Lecture #7: Recursion (and a data structure)

CSE 344 JULY 9 TH NOSQL

CSE 565 Computer Security Fall 2018

I n p u t. This time. Security. Software. sanitization ); drop table slides. Continuing with. Getting insane with. New attacks and countermeasures:

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 10: Transaction processing. November 14, Lecturer: Rasmus Pagh

CS101 Lecture 7: Internetworking:

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

Introduction to Data Management CSE 414

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

CS1 Lecture 11 Feb. 9, 2018

Microsoft Access - Using Relational Database Data Queries (Stored Procedures) Paul A. Harris, Ph.D. Director, GCRC Informatics.

What You ll Learn Today

Fall 2017 Discussion 10: November 15, Introduction. 2 Creating Tables

NetOps Coding 101 building your first robot!

Transcription:

CS108 Lecture 19: The Python DBAPI Sqlite3 database Running SQL and reading results in Python Aaron Stevens 6 March 2013 What You ll Learn Today Review: SQL Review: the Python tuple sequence. How does a custom application program connect to a database? How to get user data into SQL queries? How does the application read the results of SQL statements? 1

The Python tuple sequence tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses. t = 4,5,6 print t A single element tuple must have a trailing comma, such as (d,). The Python tuple sequence tuples are very similar to lists, but they are immutable: items in a tuple cannot be changed. tuple elements are accessed by index, or by simultaneous assignment: print t[0] a,b,c = t # unpacking a tuple 2

The Python DB API Python defines a standard API (objects and methods) for interaction with databases. No standard implementation of this interface. 3 rd party developers write their own libraries which conforms to the standard. We will be using 2 different DBMS in CS108: The SQLite3 DBMS comes standard with Python Free, nothing additional to install We ll move to the MySQL DBMS for web-application projects starting in 2 weeks Creating a sqlite3 Connection A Connection is an object that represents the database connection. Import the sqlite3 module Use connection string to specify database file name. Call connect function to obtain a Connection. 3

Obtain a Cursor object A Cursor object is an used to execute transactions (via SQL) against the database. Create the Connection first Ask the Connection object to give you a Cursor object: Executing an SQL Statement Use the Cursor object s execute method to run an SQL statement against the database. Look at the results. What type are these? 4

Processing Query Results After calling the cursor.execute() method, we can process/interpret the results. SELECT queries: results will be zero or more rows of data returned from the database INSERT, UPDATE, and DELETE queries: the result will be the number of rows (zero or more) affected by the change. Processing Query Results SELECT queries: results will be zero or more rows of data returned from the database The method cursor.fetchall() returns a tuple of rows (each row is a tuple of fields). data = cursor.fetchall() We can then process this tuple in the normal fashion using a for loop. 5

Processing Query Results A complete example, processing all rows returned from a SELECT query: Processing Query Results INSERT, UPDATE, and DELETE queries: the result will be the number of rows (zero or more) affected by the change. The attribute cursor.rowcount is an integer, the number of rows affected. 6

How to Commit the Changes? For INSERT, UPDATE, and DELETE queries, you need to execute the method: conn.commit() on the Connection object to commit your changes. It might be a good idea to only commit if the row count is reasonable (e.g. 1, not 2728). Parameterized SQL Most likely, SQL queries in an application will be dependent on some data input by the user. Don t do this: This kind of statement is vulnerable to SQL injection a major security risk. 7

SQL Injection SQL injection is a technique that exploits the syntax of SQL to chain extra statements to an SQL query. Suppose user inputs: BUD ;DROP TABLE stocks AND t = t The resulting SQL becomes: SELECT * from stocks WHERE symbol= BUD ;DROP TABLE stocks AND t = t Don t think the hackers haven t tried this! Parameterized SQL Instead, do this: and put the input parameter into a tuple: 8

Parameterized SQL Also, use parameterized SQL for INSERT statements. (assume variables symbol, name, price, earnings, yield have received user input): sql = INSERT INTO stocks VALUES (?,?,?,?,?) parameters = (symbol,name,price,earnings,yield) cursor.execute(sql, parameters) SQL Injection 9

SQL Injection Source: www.xkcd.com What You Learned Today tuple DBAPI Connection object Cursor object SQL injection! 10

Announcements and To Do Readings: SQL Tutorial (Monday) http://www.firstsql.com/tutor.htm Python DBAPI and sqlite3 (today) http://docs.python.org/library/sqlite3.html Using sqliteclient Program You may use the sqliteclient.py program to experiment with SQL statements: http://cs-webapps.bu.edu/cs108/util/sqliteclient.py Check your SQL statements against this client to rule out SQL syntax errors. Then implement the SQL with parameterized data in your client program. 11