Introduction to pysqlite

Similar documents
CSC 120 Worksheet 12 Databases

NCSS: Databases and SQL

UNIVERSITY OF TORONTO SCARBOROUGH. Wnter 2016 EXAMINATIONS. CSC A20H Duration 2 hours 45 mins. No Aids Allowed

UNIVERSITY OF TORONTO SCARBOROUGH. Fall 2015 EXAMINATIONS. CSC A20H Duration 3 hours. No Aids Allowed

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

sqlite3 DB-API 2.0 interface for SQLite databases

SQL: Programming. Introduction to Databases CompSci 316 Fall 2017

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

Developing Informix Applications in Python

Building a Test Suite

CS108 Lecture 19: The Python DBAPI

Database Design and Programming

L6 Application Programming. Thibault Sellam Fall 2018

SQL: Programming. Introduction to Databases CompSci 316 Fall 2018

POSTGRESQL - PYTHON INTERFACE

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

Python and Databases

SQLite. Nov 14, CS445 Pacific University 1 11/14/11

Overview of the sqlite3x and sq3 APIs

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

Transbase R PHP Module

Transactions for web developers

The Swiss-Army Knife for Python Web Developers. Armin Ronacher

CSE 115. Introduction to Computer Science I

PostgreSQL, Python, and Squid.

CSCD43: Database Systems Technology. Lecture 4

Storage Tier. Mendel Rosenblum. CS142 Lecture Notes - Database.js

Including Dynamic Images in Your Report

SQL: Data Sub Language

Traffic violations revisited

CF SQLite Code Generator User Manual V

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

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Now go to bash and type the command ls to list files. The unix command unzip <filename> unzips a file.

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

pymonetdb Documentation

Database extensions for fun and profit. Andrew Dalke Andrew Dalke Scientific, AB Gothenburg, Sweden

HP NonStop Structured Query Language (SQL)

CS 2316 Exam 3. Practice. Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Database Programming with SQL

CS378 -Mobile Computing. Persistence -SQLite

Lab 3 - Development Phase 2

Working with Databases and Java

CS 2316 Exam 3 ANSWER KEY

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

PYTHON MYSQL DATABASE ACCESS

Object-Relational Mapping Tools let s talk to each other!

SQL Server 2008 Tutorial 3: Database Creation

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

Database Management Systems Paper Solution

postgresql postgresql in Flask in 15 or so slides 37 slides

CS 2316 Exam 4 Fall 2012

SPL171 Assignment 4 Responsible TA s: Morad Muslimany, Itay Ariav Published on: Due date: at 23: 59

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Relational databases and SQL

Data Organization and Processing I

Logging and Recovery. 444 Section, April 23, 2009

Databases and Database Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

SQL DML and DB Applications, JDBC

Real SQL Programming 1

Firebird Database Backup by Serialized Database Table Dump

MySQL. A practical introduction to database design

COMP 430 Intro. to Database Systems. Encapsulating SQL code

CSC Java Programming, Fall Java Data Types and Control Constructs

SQL: Programming Midterm in class next Thursday (October 5)

pybdg Documentation Release 1.0.dev2 Outernet Inc

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

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

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

Instructor: Jinze Liu. Fall 2008

Problem Based Learning 2018

Android Programming Lecture 15 11/2/2011

Databases 2012 Embedded SQL

3 The Building Blocks: Data Types, Literals, and Variables

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Canvas Data Utilities Documentation

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

Data Manipulation Language

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

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

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

Beyond Blocks: Python Session #1

CLIENT/SERVER. Development of Client-/Server-Applications. Intelligent Solutions Consulting Roland Stephan. Sonntag, 15.

Armide Documentation. Release Kyle Mayes

python-tds Documentation

ALTER TABLE Improvements in MARIADB Server. Marko Mäkelä Lead Developer InnoDB MariaDB Corporation

pymapd Documentation Release dev3+g4665ea7 Tom Augspurger

Android Programming Lecture 16 11/4/2011

Reminders. Github & HTTP steps, together with the minimally viable Django product are due this coming Tuesday! CS370, Günay (Emory) Spring / 8

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

CS 2316 Exam 1 Spring 2014

SQL User Defined Code. Kathleen Durant CS 3200

Torndb Release 0.3 Aug 30, 2017

Fundamentals of Web Programming

CSE 115. Introduction to Computer Science I

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Business Analytics. SQL PL SQL [Oracle 10 g] P r i n c e S e t h i w w w. x l m a c r o. w e b s. c o m

Creating SQL Server Stored Procedures CDS Brownbag Series CDS

Transcription:

Introduction to pysqlite A crash course to accessing SQLite from within your Python programs. Based on pysqlite 2.0.

SQLite basics SQLite is embedded, there is no server Each SQLite database is stored in one file SQLite supports in-memory databases, too

SQLite basics (2) SQLite supports the following types TEXT INTEGER FLOAT BLOB NULL

SQLite basics (3) Type conversions from SQLite to Python TEXT INTEGER FLOAT BLOB NULL unicode int float buffer None

Import the module from pysqlite2 import dbapi2 as sqlite

Open a connection con = sqlite.connect( mydb.db ) If the file does not exist, an empy database is created. con = sqlite.connect( :memory: ) In-memory databases are always empty when created.

Create a cursor cur = con.cursor()

Execute a query... and fetch one row Returned rows are tuples! cur.execute( select firstname, lastname from person ) row = cur.fetchone() if row is None: # Error, no result else: firstname, lastname = row[0], row[1]

Execute a query... and process all rows The cursor is iterable, just loop over the cursor! cur.execute( select firstname, lastname from person ) for row in cur: print firstname: %s, lastname: %s % (row[0], row[1])

Queries with parameters (1) cur.execute(sql, parameters) SQL: Python string, must be encoded in UTF-8 if it contains non-ascii characters. Or: Unicode string. Parameters: Sequence (list, tuple,...) or mapping (dict).

Queries with parameters (2) Use? as placeholders and use a sequence for the parameters: cur.execute( insert into person(firstname, lastname) values (?,?), ( Gerhard, Haering ) )

Queries with parameters (3) Use :name as placeholders and use a mapping for the parameters: item = { firstname : Gerhard, lastname : Haering } cur.execute( insert into person(firstname, lastname) values (:firstname, :lastname), item )

Queries with parameters (4) Neat hack - use the fact that locals() is a mapping, too: firstname = Gerhard lastname = Haering cur.execute( insert into person(firstname, lastname) values (:firstname, :lastname), locals() )

Oops? Where's my data??? pysqlite uses transactions so that your database is always in a consistent state. To make changes permanent you must commit the changes!

Committing changes cur = con.cursor() cur.execute( insert into table1... ) cur.execute( insert into table2... ) con.commit() After database modifications that belong together logically, commit your changes so that this consistent state is stored permanently.

Roll back changes cur = con.cursor() try: cur.execute( delete from... ) cur.execute( delete from... ) con.commit() except sqlite.databaseerror: con.rollback() Roll back changes when an error occured, in order to keep your database consistent!

Be nice and clean up cur.close() con.close() You should close cursors and connections that you no longer use. Only close the connection when you've closed all cursors you created from it!

Conclusion That's it I hope you've learnt something about using SQLite from Python using pysqlite 2.0!

Resources The Wiki on http://pysqlite.org/ The pysqlite mailing list! For how SQLite works and the SQL it supports: http://sqlite.org/