final String database=
"jdbc:mysql://localhost:3306/"+ "mydb";
Connection db; db = DriverManager
.getConnection(database, "myuser",
"secretpassword");
Issue query / execute
SQL statement
Query types
Insert (Create)
Query (Read)
Update (Update)
Delete (Delete)
Frequent queries can be "prepared"
Returns a "Cursor" for
reading results
Why a "cursor"
Databases can be big
Result sets can be really big
Not all results can be
stored/transferred in memory
User might want to process
results sequentially
Query Android/SQLite
static final String SQL="SELECT *
FROM messages WHERE index=?";
Cursor result; result =
db.rawQuery(SQL, new String[]{
Long.toString(index)});
Query JDBC
static final String SQL="SELECT *
FROM messages WHERE index=?";
PreparedStatement stmt =
db.prepareStatement(SQL); stmt.setInt(0,
index); ResultSet result; result =
stmt.executeQuery();
Retrieve results
Row by Row
Generic, so "ugly"
Can tell you columns names
If you use wildcards, retrieve (and
cache) column indices
Don't forget to close result when finished
Close connection
Release resources
belonging to
connection
Must be called for
each connection
Database resources are
expensive, reuse them, but
close them when not needed
for long time db.close();
Issues with databases
Used often to store
user data
SQL is a language
Do not use string
concatenation for
variable parts
This is slower,
database doesn't know
it's the same query
This can be insecure (if the data
is not from the program)