LECTURE 21. Database Interfaces

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

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

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

Databases. Course October 23, 2018 Carsten Witt

Traffic violations revisited

CS108 Lecture 19: The Python DBAPI

postgresql postgresql in Flask in 15 or so slides 37 slides

CIS 192: Lecture 11 Databases (SQLite3)

Using SQLite in ArcGIS Python Scripts

POSTGRESQL - PYTHON INTERFACE

django-data-migration Documentation

Python for Oracle. Oracle Database Great for Data Store. Critical for Business Operations. Performance? Run in laptop? But how do you share it?

Programmers Guide. Adaptive Server Enterprise Extension Module for Python 15.7 SP100

MySQL Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP

PYTHON MYSQL DATABASE ACCESS

CS 2316 Exam 4 Fall 2011

processing data with a database

Programming in Java

Torndb Release 0.3 Aug 30, 2017

Kaivos User Guide Getting a database account 2

pymapd Documentation Release dev3+g4665ea7 Tom Augspurger

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

phoenixdb Release Nov 14, 2017

IEMS 5722 Mobile Network Programming and Distributed Server Architecture

CSE 115. Introduction to Computer Science I

Develop Python Applications with MySQL Connector/Python DEV5957

INTRODUCTION TO DATA SCIENCE

SQL I: Introduction. Relational Databases. Attribute. Tuple. Relation

CSE 115. Introduction to Computer Science I

Databases (MariaDB/MySQL) CS401, Fall 2015

L6 Application Programming. Thibault Sellam Fall 2018

Landscape Gardening AQA GCSE Computer Science Controlled Assessment

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Python and Databases

CE419 Web Programming. Session 15: Django Web Framework

Database Application Development

CGS 3066: Spring 2017 SQL Reference

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

Developing Informix Applications in Python

DATABASE SYSTEMS. Database programming in a web environment. Database System Course, 2016

pymonetdb Documentation

SQL Commands & Mongo DB New Syllabus

Development Technologies. Agenda: phpmyadmin 2/20/2016. phpmyadmin MySQLi. Before you can put your data into a table, that table should exist.

NCSS: Databases and SQL

EE221 Databases Practicals Manual

CS313D: ADVANCED PROGRAMMING LANGUAGE

HOW TO FLASK. And a very short intro to web development and databases

Relational databases and SQL

Using PHP with MYSQL

Alan Nichol Co-founder and CTO, Rasa

CS 2316 Exam 4 Fall 2012

Transactions for web developers

DATABASE MANAGEMENT SYSTEMS PREPARED BY: ENGR. MOBEEN NAZAR

2 Name any 3 widgets that you have used in programming (3) ComboBox, LineEdit, Calendar Widget, LCD Widget

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

NCSS: Databases and SQL

EXAM PGCES-02. PostgreSQL CE 8 Silver Exam.

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus Lecture #23: SQLite

Lecture 5. Monday, September 15, 2014

Mysql Tutorial Show Table Like Name Not >>>CLICK HERE<<<

CSC326 Persistent Programming i. CSC326 Persistent Programming

SQL: Transactions. Introduction to Databases CompSci 316 Fall 2017

Automating Reports with Python. Gem Stone-Logan Technology Librarian Mountain View Public Library Mountain View, CA

DATABASE SYSTEMS. Database programming in a web environment. Database System Course,

CS352 Lecture - Introduction to SQL

pymssql Documentation

pymssql Documentation

COMP 430 Intro. to Database Systems. Encapsulating SQL code

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

Homework 1. Hadachi&Lind October 25, Deadline for doing homework is 3 weeks starting from now due date is:

Alyssa Grieco. Data Wrangling Final Project Report Fall 2016 Dangerous Dogs and Off-leash Areas in Austin Housing Market Zip Codes.

Oracle Compare Two Database Tables Sql Query Join

Using Relational Databases for Digital Research

Database Connectivity using PHP Some Points to Remember:

MariaDB ColumnStore PySpark API Usage Documentation. Release d1ab30. MariaDB Corporation

CS 2316 Homework 9a GT Room Reservation Login

Chapter 16: Databases

CS 2316 Exam 4 Spring 2013

CS 2316 Exam 4 Fall 2011

Database Application Development

MTAT Introduction to Databases

Databases and SQL programming overview

DCOracle2 User s Guide & Reference

PyMySQL Documentation

pyfirebirdsql documentation

CS108 Lecture 18: Databases and SQL

Essential Skills - RDBMS and SQL

Learn SQL by Calculating Customer Lifetime Value

Queries Documentation

Microsoft SQL Server Week1

CS 250 SQL and SQLite. Benjamin Dicken

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

DATA STRUCTURES USING C

SQL: Programming. Introduction to Databases CompSci 316 Fall 2017

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1.

HIBERNATE MOCK TEST HIBERNATE MOCK TEST IV

Operating systems fundamentals - B07

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population

pysqlw Documentation Release plausibility

Transcription:

LECTURE 21 Database Interfaces

DATABASES Commonly, Python applications will need to access a database of some sort. As you can imagine, not only is this easy to do in Python but there is a ton of support for various relational and non-relational databases. Databases for which there is module support include: MySQL PostgreSQL Oracle SQLite Cassandra MongoDB etc

DATABASES Even for a certain database, there are a number of module options. For example, MySQL alone has the following interface modules: MySQL for Python (import MySQLdb) PyMySQL (import pymysql) pyodbc (import pyodbc) MySQL Connector/Python (import mysql.connector) mypysql (import mypysql) etc Yes, for every combination of my, py, and sql, there is someone out there with a better implementation of a MySQL module.

DATABASE API SPECIFICATION So which module do you choose? Well, as far as code-writing goes, it probably won t make that much of a difference Python Enhancement Proposal 249 provides the API specification for modules that interface with databases. You can access the specification here. The majority of database modules conform to the specification so no matter which kind of database and/or module you choose, the code will likely look very similar.

DATABASE API SPECIFICATION The module interface is required to have the following: connect(args) a constructor for Connection objects, through which access is made available. Arguments are database-dependent. Globals apilevel (DB API level 1.0 or 2.0), threadsafety (integer constant indicating thread safety status), paramstyle (string constant indicating query parameter style). A number of exceptions, including IntegrityError, OperationalError, DataError, etc.

DATABASE API SPECIFICATION A little more about paramstyle: the defined string constants are shown below along with an example of each. Constant qmark numeric named format pyformat Meaning Question mark style, e.g....where name=? Numeric, positional style, e.g....where name=:1 Named style, e.g....where name=:name ANSI C printf format codes, e.g....where name=%s Python extended format codes, e.g....where name=%(name)s

DATABASE API SPECIFICATION So assuming conn = connect(args) yields a Connection object, we should be able to manipulate our connection via the following methods: conn.close() close connection. conn.commit() commit pending transaction. conn.rollback() if supported by db, roll back to start of pending transaction. conn.cursor() return a Cursor object for the connection.

DATABASE API SPECIFICATION So c = conn.cursor() should yield a Cursor object. We can have multiple cursors per connection, but they are not isolated from one another. The following attributes should be available: c.description a description of the cursor with up to seven fields. c.rowcount number of rows produced by last execute method.

DATABASE API SPECIFICATION So c = conn.cursor() should yield a Cursor object. We can have multiple cursors per connection, but they are not isolated from one another. The following methods should be available: c.execute[many](op, [params]) prepare and execute an operation with parameters where the second argument may be a list of parameter sequences. c.fetch[one many all]([s]) fetch next row, next s rows, or all remaining rows of result set. c.close() close cursor. and others.

DATABASE API SPECIFICATION There are a number of optional extensions such as the rownumber attribute for cursors, which specifies the current row of the result set. There are also additional implementation requirements that are not necessary to be familiar with as a user of the module. So now we basically understand how most of Python s database modules work.

SQLITE3 To get a feel for database usage in Python, we ll play around with the sqlite3 module, which is a part of the standard library. SQLite is a lightweight C-based relational database management system which uses a variant of the SQL language. The data is essentially stored in a file which is manipulated by the functions of the C library that implements SQLite.

SQLITE3 The very first thing we ll need is to build an sqlite3 database to mess around with. Building off of our Gooey Blackjack application, let s build a database for tracking most winningest (yep) sessions. When a user plays a session, they ll have the option of recording their name and number of winning games in the database. We ll then add a menu bar option that allows the user to see the top three players in terms of number of wins per session.

SQLITE3 I ll start by creating my SQLite database with the sqlite3 command line tool. My database file is highscores.db. My table is called Scores. I have two columns: name and wins. Now, I just need to modify my GUI with the functionality to add and views records in the database. Also check out the Firefox SQLite manager. $ sqlite3 highscores.db SQLite version 3.7.7 2011-06-23 19:49:22 Enter ".help" for instructions Enter SQL statements terminated with a "; sqlite> create table Scores(name varchar(10), wins smallint); sqlite> insert into Scores('Caitlin', 3); Error: near "3": syntax error sqlite> insert into Scores('Caitlin',3); Error: near "3": syntax error sqlite> insert into Scores values ('Caitlin', 3); sqlite> insert into Scores values ('Ben', 4); sqlite> insert into Scores values ('Melina', 2); sqlite> select * from Scores; Caitlin 3 Ben 4 Melina 2 sqlite>

DB_INTERFACE.PY I m going to add to my application a python module responsible for connecting to my SQLite database and inserting/grabbing data. import sqlite3 def top_scores(): # Returns top three highest winners conn = sqlite3.connect("highscores.db") c = conn.cursor() c.execute("select * FROM Scores ORDER BY wins DESC;") result_rows = c.fetchmany(3) conn.close() return result_rows def insert_score(name, wins): # Inserts a name and score conn = sqlite3.connect("highscores.db") c = conn.cursor() c.execute("insert INTO Scores VALUES (?,?);", (name, wins)) conn.commit() conn.close() if name == " main ": for s in top_scores(): print s

DEMO Let s take a look at our updated Gooey Blackjack application.

MYSQLDB import MySQLdb db = MySQLdb.connect( localhost, username", password, EmployeeData ) cursor = db.cursor() sql = "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE) VALUES ('%s', '%s', '%d')" % ( Caitlin', Carnahan', 24) try: cursor.execute(sql) db.commit() except: db.rollback() db.close()

PSYCOPG2 import psycopg2 db = psycopg2.connect (database= mydatabase", user= uname", password="pword") c = db.cursor() c.execute ("SELECT * FROM versions"); rows = c.fetchall() for i, row in enumerate(rows): print "Row", i, "value = ", row c.execute ("DELETE FROM versions") c.execute ("DROP TABLE versions") c.close() db.close()