Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Module : java.sql
Version documentée : Java SE 17

Le paquetage java.sql

Description du paquetage

L'API JDBC (Java DataBase Connectivity) permet la connexion et la manipulation d'une base de données relationnelle.

Exemple de code

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
package fr.koor.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class MainFrame {

    // Les informations de connexion à la base de données.
    private static final String JDBC_URL = "jdbc:mysql://localhost/<dbname>";
    private static final String JDBC_LOGIN = "<username>";
    private static final String JDBC_PASSWORD = "<password>";
    
    
    public static void main( String[] args ) {
        
        System.out.println( "Welcome to this super app." );
        
        // On lance un scanner sur la console, pour y permettre la saisie
        // ainsi qu'une connexion à la base de données.
        try ( Scanner scanner = new Scanner( System.in ) ;
              Connection connection = DriverManager.getConnection( JDBC_URL, JDBC_LOGIN, JDBC_PASSWORD ) ) {

            // On demande le prix maximum des articles à sélectionner.
            System.out.print( "Prix maximum : " );
            int maxPrice = Integer.parseInt( scanner.nextLine() );
            
            // On prépare l'ordre SQL à envoyer en base de données.
            String sql = "SELECT * FROM T_Articles WHERE unitaryPrice <= ?";
            try ( PreparedStatement statement = connection.prepareStatement( sql ) ) {

                statement.setInt( 1, maxPrice );    // Les indices de paramètres commencent à 1
                
                // On envoie l'ordre SQL en base et on récupère les résultats.
                try ( ResultSet resultSet = statement.executeQuery() ) {
                    while ( resultSet.next() ) {
                        System.out.printf( "%3d: %-20s %-20s = %.2f\n",
                                resultSet.getInt( "idArticle" ),
                                resultSet.getString( "description" ),
                                resultSet.getString( "brand" ),
                                resultSet.getDouble( "unitaryPrice" ) );
                    }
                }
                
            }

        } catch( Exception exception ) {
            System.err.println( "Connection à la base de données impossible (" + exception.getMessage() + ")" );
        }
        
        System.out.println( "Bye bye" );
    }
    
}


/*
 * Pour informations, voici un exemple de code de définition d'une table T_Articles.
 * 
 * CREATE TABLE T_Articles (
 *     idArticle           int(4)      PRIMARY KEY AUTO_INCREMENT,
 *     description         text        NOT NULL,
 *     brand               text        NOT NULL,
 *     unitaryPrice        float(8)    NOT NULL
 * );
 * 
 */
Exemple de connexion à une base de données via l'API JDBC.

Disponible depuis

1.1

Voir aussi

Quelques ressources complémentaires sur JDBC.

Contenu du paquetage

Interfaces

NomDescription
Array
Blob
CallableStatement
Clob
Connection
ConnectionBuilder
DatabaseMetaData
Driver
DriverAction
NClob
ParameterMetaData
PreparedStatement
Ref
ResultSet
ResultSetMetaData
RowId
SQLData
SQLInput
SQLOutput
SQLType
SQLXML
Savepoint
ShardingKey
ShardingKeyBuilder
Statement
Struct
Wrapper

Classes

NomDescription
Date
DriverManager
DriverPropertyInfo
SQLPermission
Time
Timestamp
Types

Types énumérés

NomDescription
ClientInfoStatus
JDBCType
PseudoColumnUsage
RowIdLifetime

Exceptions

NomDescription
BatchUpdateException
DataTruncation
SQLClientInfoException
SQLDataException
SQLException
SQLFeatureNotSupportedException
SQLIntegrityConstraintViolationException
SQLInvalidAuthorizationSpecException
SQLNonTransientConnectionException
SQLNonTransientException
SQLRecoverableException
SQLSyntaxErrorException
SQLTimeoutException
SQLTransactionRollbackException
SQLTransientConnectionException
SQLTransientException
SQLWarning