Databases

Table of Contents

Database Application Programming

Various ways of using database tech:

Using database tech

how to access database from apps:

Dynamic

JDBC

provides APIs like getInt(string), getString(string) to fetch cols by name. can run executeQuery(sql query) to run SQL statements.

matches approx. SQL types to Java types, not always precise (String vs VARCHAR(20))

SQL types to Java

to improve performance of JDBC apps:

SQL injection

Exploit SQL statement construction to run your own commands.

Wrong:

stat.executeQuery("SELECT balance FROM accounts " + "WHERE name = '" + userName + "'" + " AND passwd = '" + userPassword + "'");

So if you fill '; SELECT * FROM accounts, it will show all accounts. You can also then update, drop, and do anything you want.

Solution: don't use string concatenation, use prepared statements.

stat = conn.prepareStatement("SELECT balance FROM accounts " + "WHERE name = ? " + " AND passwd = ?");
stat.setString(1, userName);
stat.setString(2, userPassword);
stat.executeQuery();

Impedance mismatch

database query language does not match app programming language.

static API (SQLJ):

dynamic API (JDBC):

an object relational mapping is one attempt to improve even more.

Object Relational Mapping

maps rows in tables to objects:

mapping from objects to database (automatic/designed). run-time library handles interaction with database.

JPA ORM example

but you might end up being inefficient and doing a huge amount of stuff in Java that you could just do in SQL and have the DBMS optimise it for you.

JPA/Hibernate HQL queries:

Important aspects of ORM toolkits:

Challenges of ORM:

ADO.NET entity framework

LinQ

Language Integrated Query. you can query data structures using SQL-like syntax

advantages:

disadvantages:

so you can do like

int[] my array = new int[] { 5, 3, 2, 6, 4, 2, 5 };
var oddNumbers = from i in myarray where i \% 2 == 1 select i;

the LinQ runtime translates that to an SQL query, and converts returned rows to objects. provides change tracking, concurrency control, object identity.

under the hood, the LinQ query is actually chained function calls with lambda expressions.