Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MariaDB extends PhoneBookModel{
- private static final String dbClassName = "org.mariadb.jdbc.Driver";
- private static final String CONNECTION = "jdbc:mariadb://localhost:3306/test";
- private final String USER = "root";
- private final String PASS = "123456";
- public MariaDB(PhoneBookView view){
- super(view);
- }
- public void save(){
- Connection conn = null;
- Statement stmt = null;
- try {
- Class.forName(dbClassName);
- // System.out.println("Connecting to a selected database...");
- conn = DriverManager.getConnection(CONNECTION, USER, PASS);
- // System.out.println("Connected database successfully...");
- stmt = conn.createStatement();
- stmt.execute("SELECT * FROM `test`.`phonebook`");
- ResultSet rs = stmt.getResultSet();
- while (rs.next()){
- stmt.execute("DELETE FROM `test`.`phonebook` WHERE `Name`='" + rs.getString("Name") + "'");
- }
- Set<String> keys = phoneBook.keySet();
- for(String key: keys){
- stmt.execute("INSERT INTO `test`.`phonebook` (`Name`, `Number`) VALUES ('" +key+"','"+phoneBook.get(key)+"')");
- }
- }catch (SQLException se) {
- //Handle errors for JDBC
- se.printStackTrace();
- } catch (Exception e) {
- //Handle errors for Class.forName
- e.printStackTrace();
- } finally{
- try {
- if (stmt != null) {
- conn.close();
- }
- } catch (SQLException se) {
- }
- try {
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- }
- public void restored(){
- Connection conn = null;
- Statement stmt = null;
- try {
- Class.forName(dbClassName);
- // System.out.println("Connecting to a selected database...");
- conn = DriverManager.getConnection(CONNECTION, USER, PASS);
- // System.out.println("Connected database successfully...");
- stmt = conn.createStatement();
- stmt.execute("SELECT * FROM `test`.`phonebook`");
- ResultSet rs = stmt.getResultSet();
- while (rs.next()) {
- phoneBook.put(rs.getString("Name"), rs.getString("Number"));
- }
- }catch (SQLException se) {
- //Handle errors for JDBC
- se.printStackTrace();
- } catch (Exception e) {
- //Handle errors for Class.forName
- e.printStackTrace();
- } finally{
- try {
- if (stmt != null) {
- conn.close();
- }
- } catch (SQLException se) {
- }
- try {
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment