Pythalex
4/18/2019 - 2:22 PM

JAVA - interagir avec une BDD

import java.util.ArrayList;
import java.util.List;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Hello world!
 *
 */
public class App 
{
    public static Connection connect(String databasePath) {
        Connection conn = null;

        try {
            String url = "jdbc:sqlite:test.sqlite";

            conn = DriverManager.getConnection(url);

        } catch (SQLException e) {
            e.printStackTrace();
        } 

        return conn;
    }

    public static void main( String[] args )
    {
        System.out.println("Trying insert.");
        if (insert("let's booboo"))
            System.out.println("Insert successfully executed.");
        else
            System.out.println("Insert could not be executed.");
        
        System.out.println("Trying select.");
        List<String> rows = select();
        if (rows != null){
            System.out.println("Rows:");
            for (String msg: rows){
                System.out.println(msg);
            }
        } else {
            System.out.println("No rows.");
        }
    }

    public static Boolean insert(String msg){
        String path = "test.sqlite";
        String query = "insert into post(msg) values(?)";

        boolean failed = false;

        try (Connection conn = connect(path);
             PreparedStatement pstmt = conn.prepareStatement(query)) {

            pstmt.setString(1, msg);
            pstmt.executeUpdate();

        } catch (SQLException e){
            e.printStackTrace();
            failed = true;
        } catch (NullPointerException e){
            System.err.println("Connection could not be opened, insert statement aborted.");
            failed = true;
        }

        return !failed;
    }

    public static List<String> select(){
        String path = "test.sqlite";
        String query = "select msg from post";

        List<String> rows = new ArrayList<String>();

        try (Connection conn = connect(path);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()){
                rows.add(rs.getString("msg"));
            }

        } catch (SQLException e){
            e.printStackTrace();
        } catch (NullPointerException e){
            System.err.println("Connection could not be opened, select statement aborted.");
        }

        return rows;
    }
}