Ricerca…


introduzione

L'API per utilizzare un database relazionale da Java è JDBC.

Questa API è implementata da un driver JDBC.

Per usarlo, inserisci il file JAR con il driver sul percorso di classe JAVA.

Questa documentazione mostra esempi su come utilizzare il driver JDBC per connettersi a un database.

Osservazioni

URL JDBC

L'URL JDBC può assumere una di queste forme:

  • jdbc:postgresql:// host [: port ]/[ database ][ parameters ]

    host predefinito su localhost , port su 5432.
    Se l' host è un indirizzo IPv6, deve essere racchiuso tra parentesi quadre.
    Il nome del database predefinito è uguale al nome dell'utente che si connette.

    Per implementare il failover, è possibile avere diverse voci host [: port ] separate da una virgola.
    Vengono provati a turno fino a quando una connessione ha esito positivo.

  • jdbc:postgresql: database [ parameters ]

  • jdbc:postgresql:/[ parameters ]

    Queste forme sono per le connessioni a localhost .

parameters è una lista di coppie key [= value ] , con a capo ? e separati da & . Se il value è mancante, si presume che sia true .

Un esempio:

jdbc:postgresql://localhost/test?user=fred&password=secret&ssl&sslfactory=org.postgresql.ssl.NonValidatingFactory

Riferimenti

Connessione con java.sql.DriverManager

Questo è il modo più semplice per connettersi.

Innanzitutto, il driver deve essere registrato con java.sql.DriverManager modo che sappia quale classe utilizzare.
Questo viene fatto caricando la classe del driver, in genere con java.lang.Class.forname( <driver class name> ) .

/**
 * Connect to a PostgreSQL database.
 * @param url the JDBC URL to connect to; must start with "jdbc:postgresql:"
 * @param user the username for the connection
 * @param password the password for the connection
 * @return a connection object for the established connection
 * @throws ClassNotFoundException if the driver class cannot be found on the Java class path
 * @throws java.sql.SQLException if the connection to the database fails
 */
private static java.sql.Connection connect(String url, String user, String password)
    throws ClassNotFoundException, java.sql.SQLException
{
    /*
     * Register the PostgreSQL JDBC driver.
     * This may throw a ClassNotFoundException.
     */
    Class.forName("org.postgresql.Driver");
    /*
     * Tell the driver manager to connect to the database specified with the URL.
     * This may throw an SQLException.
     */
    return java.sql.DriverManager.getConnection(url, user, password);
}

Non è possibile includere anche l'utente e la password nell'URL JDBC, nel qual caso non è necessario specificarli nella chiamata al metodo getConnection .

Connessione con java.sql.DriverManager e Proprietà

Invece di specificare i parametri di connessione come utente e password (vedere qui un elenco completo) nell'URL o parametri separati, è possibile comprimerli in un oggetto java.util.Properties :

/**
 * Connect to a PostgreSQL database.
 * @param url the JDBC URL to connect to. Must start with "jdbc:postgresql:"
 * @param user the username for the connection
 * @param password the password for the connection
 * @return a connection object for the established connection
 * @throws ClassNotFoundException if the driver class cannot be found on the Java class path
 * @throws java.sql.SQLException if the connection to the database fails
 */
private static java.sql.Connection connect(String url, String user, String password)
    throws ClassNotFoundException, java.sql.SQLException
{
    /*
     * Register the PostgreSQL JDBC driver.
     * This may throw a ClassNotFoundException.
     */
    Class.forName("org.postgresql.Driver");
    java.util.Properties props = new java.util.Properties();
    props.setProperty("user", user);
    props.setProperty("password", password);
    /* don't use server prepared statements */
    props.setProperty("prepareThreshold", "0");
    /*
     * Tell the driver manager to connect to the database specified with the URL.
     * This may throw an SQLException.
     */
    return java.sql.DriverManager.getConnection(url, props);
}

Connessione con javax.sql.DataSource utilizzando un pool di connessioni

È comune utilizzare javax.sql.DataSource con JNDI nei contenitori del server delle applicazioni, in cui si registra un'origine dati con un nome e si effettua la ricerca ogni volta che è necessaria una connessione.

Questo è un codice che dimostra come funzionano le origini dati:

/**
 * Create a data source with connection pool for PostgreSQL connections
 * @param url the JDBC URL to connect to. Must start with "jdbc:postgresql:"
 * @param user the username for the connection
 * @param password the password for the connection
 * @return a data source with the correct properties set
 */
private static javax.sql.DataSource createDataSource(String url, String user, String password)
{
    /* use a data source with connection pooling */
    org.postgresql.ds.PGPoolingDataSource ds = new org.postgresql.ds.PGPoolingDataSource();
    ds.setUrl(url);
    ds.setUser(user);
    ds.setPassword(password);
    /* the connection pool will have 10 to 20 connections */
    ds.setInitialConnections(10);
    ds.setMaxConnections(20);
    /* use SSL connections without checking server certificate */
    ds.setSslMode("require");
    ds.setSslfactory("org.postgresql.ssl.NonValidatingFactory");

    return ds;
}

Una volta creata un'origine dati chiamando questa funzione, la utilizzerai in questo modo:

/* get a connection from the connection pool */
java.sql.Connection conn = ds.getConnection();

/* do some work */

/* hand the connection back to the pool - it will not be closed */
conn.close();


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow