Ci sono vari tipi o modelli di database ma il piu' comune e' il database relazionale che si presenta appunto come una serie di tabelle e di relazioni tra le stesse. Inoltre nel gergo dei database relazionali le righe di una tabella sono record e le colonne sono campi(fields in inglese). Ogni campo e' individuato da un nome ed ogni record da uno o piu' campi particolari che fanno da identificatore o chiave primaria dello stesso. I DBMS piu' diffusi come Filemaker , Oracle e Access sono relazionali. Ma un altro tipo di database, quello ad oggetti, si sta diffondendo in seguito al successo dei linguaggi di programmazione ad oggetti.
Per i data base relazionali o RDBMS e' stato creato un linguaggio standard di creazione e interrogazione di database che permette la comunicazione con RDBMS . Il linguaggio si chiama SQL o Structured Query Language ed e' capito dalla maggioranza dei database(nel nostro caso Access e MySql capiscono l'SQL , Filemaker no). Un programma che acceda a un database usando SQL dovrebbe poter essere usato con database di diverso tipo,basta che capiscano l'SQL. Perche' questo avvenga il costruttore di ogni database deve fornire un insieme di classi detto JDBC driver che contiene le caratteristiche specifiche del database.
Questo significa che se volete accedere a un database,ad es. MySQL, dovete:
file Employee.java
import java.sql.*;
class Employee
{
public static void main (String args [])
{
try {
// Load the MySQL JDBC driver
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e) {
System.out.println ("MySQL device driver does not exist");
System.exit(1);
}
// Connect to the database
// You can put a database name after the @ sign in the connection URL.
Connection conn =
DriverManager.getConnection ("jdbc:mysql://localhost/rpc?user=pinco&password=pallino");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("SELECT ID, ChamberID, Chamber_type, Status from Chamber");
// Iterate through the result and print the employee names
while (rset.next ()) {
System.out.print ("Name "+rset.getString (1));
System.out.print (" Job "+rset.getString(2));
System.out.print (" Salary "+ rset.getString(3));
System.out.println (" HDate "+ rset.getString(4));
}
// Close the RseultSet
rset.close();
// Close the Statement
stmt.close();
// Close the connection
conn.close();
} catch (SQLException e) {
System.out.println("Error accessing DB ");
System.out.println(" Error code is : "+e.getErrorCode());
System.out.println(" Error message is :"+e.getMessage());
}
}
}
Connection permette di connettersi al database.
Statement permette di fare la query in SQL.
ResultSet permette di ottenere le righe risultato della domanda.