Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package base;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.util.ArrayList;
- import java.util.ResourceBundle;
- import bean.Livre;
- public class Base {
- static {
- try{
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- }
- catch(Exeption e){
- }
- }
- Connection connection = null;
- public Base() {
- String url = null;
- String user = null;
- String password = null;
- // accès au ressources (fichier base/config.properties)
- try {
- ResourceBundle rs =
- ResourceBundle.getBundle("base/config");
- url = rs.getString("url");
- user = rs.getString("user");
- password = rs.getString("password");
- System.out.println("url = "+url);
- System.out.println("user = "+user);
- }
- catch (Exception e) {
- System.out.println("Erreur acces ressources "+e.getMessage());
- }
- // connexion BD
- try {
- connection = DriverManager.getConnection(url, user, password);
- }
- catch (Exception e) {
- System.out.println("Erreur connexion "+e.getMessage());
- }
- }
- public void fermer() {
- try {if (connection != null) connection.close();} catch (Exception e) {}
- }
- public ArrayList<Livre> listerLivres() {
- ArrayList<Livre> res = new ArrayList<>();
- String sql = "select * from t_livre";
- try {
- PreparedStatement ps = connection.prepareStatement(sql);
- ResultSet rs = ps.executeQuery();
- while (rs.next()) {
- int idLivre = rs.getInt("idLivre");
- String titre = rs.getString("titre");
- String auteur = rs.getString("auteur");
- int annee = rs.getInt("annee");
- Livre l = new Livre(titre, auteur, annee);
- l.setIdLivre(idLivre);
- res.add(l);
- }
- }
- catch (Exception e) {
- System.out.println(
- "Erreur listerLivres "+e.getMessage());
- }
- return res;
- }
- public boolean enregistrerLivre(Livre l) {
- boolean res = false;
- String sql = "insert into t_livre (titre, auteur, annee) values (?, ?, ? )";
- try {
- PreparedStatement ps = connection.prepareStatement(sql);
- ps.setString(1, l.getTitre());
- ps.setString(2, l.getAuteur());
- ps.setInt(3, l.getAnnee());
- System.out.println("sql = " +ps.toString());
- int nb = ps.executeUpdate();
- if (nb == 1) res = true;
- } catch (Exception e) {
- System.out.println(
- "Erreur enregistrerLivre "+e.getMessage());
- }
- return res;
- }
- public static void main(String [] args) {
- Base base = new Base();
- Livre livre = new Livre
- ("titreB","auteurB",2019);
- base.enregistrerLivre(livre);
- ArrayList<Livre> lst = base.listerLivres();
- for (Livre l : lst) {
- System.out.println("titre = "+l.getTitre());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement