Saeid Zebardast @saeid http://about.me/saeid saeid.zebardast@gmail.com 1
Please Please Please Ask Questions As Much As You Like • This is not a lecture! - But an opportunity to learn from each other. - If you haven’t seen some of these frameworks, methods, etc. It is OK! - Let we know if you know ‣ Better ways ‣ Best practices ‣ My mistakes!
Requirements • Java (OpenJDK) • MySQL • MySQL Connector - JDBC (Java Database Connectivity) ‣ https://dev.mysql.com/downloads/connector/j/ • Text Editor • Command Line! 3
MySQL Data Definition • Create database - $ mysql -u root -p ‣ mysql> CREATE DATABASE phonebook_app; • Create database user - $ mysql -u root -p ‣ mysql> GRANT ALL PRIVILEGES on `phonebook_app`.* to `pb_app`@'127.0.0.1' identified by '123456'; • Create table - $ mysql -u pb_app -p phonebook_app ‣ mysql> CREATE TABLE `contact` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(100), `last_name` VARCHAR(100), `email` VARCHAR(100), `mobile` VARCHAR(15), PRIMARY KEY (`id`) ); 4
Java Classes Contact • Contact - Fields ‣ long id ‣ String firstName ‣ String lastName ‣ String email ‣ String mobile - Methods ‣ Contact() ‣ Getters for all fields: getId(), getFirstName() and etc. 5
Java Classes PhonebookApp • PhonebookApp - Import java.sql.* and java.util.*; - Fields ‣ Connection con; ‣ PreparedStatement pst; ‣ ResultSet rs; ‣ String url; ‣ String user; ‣ String password; 6 - Methods ‣ PhonebookApp() ‣ main() ‣ printHelp() ‣ showList() ‣ add() ‣ delete() ‣ closeAllConnections()
Create Content Class public class Contact { private long id; private String firstName; private String lastName; private String email; private String mobile; Contact(long id, String firstName, String lastName, String email, String mobile) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; this.mobile = mobile; } // getter here } 7
Create PhonebookApp Class Fields and Constructor public class PhonebookApp { Connection con; PreparedStatement pst; ResultSet rs; String url; String user; String password; PhonebookApp() { url = "jdbc:mysql://127.0.0.1:3306/phonebook_app"; user = "pb_app"; password = "123456"; } //write methods here } 8
Create PhonebookApp Class Methods: main() public static void main(String[] args) { if (args == null || args.length == 0) { printHelp(); return; } PhonebookApp phonebookApp = new PhonebookApp(); switch (args[0]) { case "list" : phonebookApp.showList(); break; case "add" : phonebookApp.add(args); break; case "delete" : phonebookApp.delete(args); break; default : printHelp(); } } 9
Create PhonebookApp Class Methods: printHelp() static void printHelp() { System.out.println("Usage: java PhonebookApp [OPTIONS]"); System.out.println("Options: add FIRST_NAME LAST_NAME EMAIL MOBILE"); System.out.println("Options: list"); System.out.println("Options: delete ID”); } 10
Create PhonebookApp Class Methods: showList() void showList() { List<Contact> contactList = new ArrayList<>(); try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("SELECT * FROM contact"); rs = pst.executeQuery(); while (rs.next()) { contactList.add(new Contact(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"), rs.getString("email"), rs.getString("mobile"))); } if (contactList.size() > 0) { for (Contact contact : contactList) { System.out.println(contact.getId() + "-" + contact.getFirstName() + " " + contact.getLastName() + ": Email = '" + contact.getEmail() + "', Mobile = '" + contact.getMobile() + "'."); } } else { System.out.println("You don't have any contacts in your list!"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { closeAllConnections(); } } 11
Create PhonebookApp Class Methods: add() void add(String[] args) { if (args.length != 5) { System.out.println("Error: Wrong Usage!"); printHelp(); } else { try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("INSERT INTO contact(first_name, last_name, email, mobile) value (?,?,?,?) "); int index = 1; pst.setString(index, args[index++]); pst.setString(index, args[index++]); pst.setString(index, args[index++]); pst.setString(index, args[index++]); pst.executeUpdate(); } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { closeAllConnections(); } } } 12
Create PhonebookApp Class Methods: delete() void delete(String[] args) { if (args.length != 2) { System.out.println("Error: Wrong Usage!"); printHelp(); } else { long id = Integer.parseInt(args[1]); if (id < 1) { System.out.println("Error: id is not valid!"); } else { try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("DELETE FROM contact where id = ? "); pst.setLong(1, id); pst.executeUpdate(); } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { closeAllConnections(); } } } } 13
Create PhonebookApp Class Methods: closeAllConnections() void closeAllConnections() { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } 14
Compile and Run PhonebookApp • compile - javac PhonebookApp.java • run - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp list - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp add myFirstName myLastName myEmail myMobile - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp delete 2 15
Read The F* Manual • RTFM - https://dev.mysql.com/doc/ - http://docs.oracle.com/javase/ • Java: The Really Big Index - http://docs.oracle.com/javase/tutorial/reallybigindex.html • MySQL Help - mysql> HELP; - mysql> HELP CONTENTS; - mysql> HELP SELECT; 16
Thank You

Developing Applications with MySQL and Java for beginners

  • 1.
    Saeid Zebardast @saeid http://about.me/saeid saeid.zebardast@gmail.com 1
  • 2.
    Please Please Please Ask Questions As Much As You Like • This is not a lecture! - But an opportunity to learn from each other. - If you haven’t seen some of these frameworks, methods, etc. It is OK! - Let we know if you know ‣ Better ways ‣ Best practices ‣ My mistakes!
  • 3.
    Requirements • Java(OpenJDK) • MySQL • MySQL Connector - JDBC (Java Database Connectivity) ‣ https://dev.mysql.com/downloads/connector/j/ • Text Editor • Command Line! 3
  • 4.
    MySQL Data Definition • Create database - $ mysql -u root -p ‣ mysql> CREATE DATABASE phonebook_app; • Create database user - $ mysql -u root -p ‣ mysql> GRANT ALL PRIVILEGES on `phonebook_app`.* to `pb_app`@'127.0.0.1' identified by '123456'; • Create table - $ mysql -u pb_app -p phonebook_app ‣ mysql> CREATE TABLE `contact` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(100), `last_name` VARCHAR(100), `email` VARCHAR(100), `mobile` VARCHAR(15), PRIMARY KEY (`id`) ); 4
  • 5.
    Java Classes Contact • Contact - Fields ‣ long id ‣ String firstName ‣ String lastName ‣ String email ‣ String mobile - Methods ‣ Contact() ‣ Getters for all fields: getId(), getFirstName() and etc. 5
  • 6.
    Java Classes PhonebookApp • PhonebookApp - Import java.sql.* and java.util.*; - Fields ‣ Connection con; ‣ PreparedStatement pst; ‣ ResultSet rs; ‣ String url; ‣ String user; ‣ String password; 6 - Methods ‣ PhonebookApp() ‣ main() ‣ printHelp() ‣ showList() ‣ add() ‣ delete() ‣ closeAllConnections()
  • 7.
    Create Content Class public class Contact { private long id; private String firstName; private String lastName; private String email; private String mobile; Contact(long id, String firstName, String lastName, String email, String mobile) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; this.mobile = mobile; } // getter here } 7
  • 8.
    Create PhonebookApp Class Fields and Constructor public class PhonebookApp { Connection con; PreparedStatement pst; ResultSet rs; String url; String user; String password; PhonebookApp() { url = "jdbc:mysql://127.0.0.1:3306/phonebook_app"; user = "pb_app"; password = "123456"; } //write methods here } 8
  • 9.
    Create PhonebookApp Class Methods: main() public static void main(String[] args) { if (args == null || args.length == 0) { printHelp(); return; } PhonebookApp phonebookApp = new PhonebookApp(); switch (args[0]) { case "list" : phonebookApp.showList(); break; case "add" : phonebookApp.add(args); break; case "delete" : phonebookApp.delete(args); break; default : printHelp(); } } 9
  • 10.
    Create PhonebookApp Class Methods: printHelp() static void printHelp() { System.out.println("Usage: java PhonebookApp [OPTIONS]"); System.out.println("Options: add FIRST_NAME LAST_NAME EMAIL MOBILE"); System.out.println("Options: list"); System.out.println("Options: delete ID”); } 10
  • 11.
    Create PhonebookApp Class Methods: showList() void showList() { List<Contact> contactList = new ArrayList<>(); try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("SELECT * FROM contact"); rs = pst.executeQuery(); while (rs.next()) { contactList.add(new Contact(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"), rs.getString("email"), rs.getString("mobile"))); } if (contactList.size() > 0) { for (Contact contact : contactList) { System.out.println(contact.getId() + "-" + contact.getFirstName() + " " + contact.getLastName() + ": Email = '" + contact.getEmail() + "', Mobile = '" + contact.getMobile() + "'."); } } else { System.out.println("You don't have any contacts in your list!"); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { closeAllConnections(); } } 11
  • 12.
    Create PhonebookApp Class Methods: add() void add(String[] args) { if (args.length != 5) { System.out.println("Error: Wrong Usage!"); printHelp(); } else { try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("INSERT INTO contact(first_name, last_name, email, mobile) value (?,?,?,?) "); int index = 1; pst.setString(index, args[index++]); pst.setString(index, args[index++]); pst.setString(index, args[index++]); pst.setString(index, args[index++]); pst.executeUpdate(); } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { closeAllConnections(); } } } 12
  • 13.
    Create PhonebookApp Class Methods: delete() void delete(String[] args) { if (args.length != 2) { System.out.println("Error: Wrong Usage!"); printHelp(); } else { long id = Integer.parseInt(args[1]); if (id < 1) { System.out.println("Error: id is not valid!"); } else { try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("DELETE FROM contact where id = ? "); pst.setLong(1, id); pst.executeUpdate(); } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { closeAllConnections(); } } } } 13
  • 14.
    Create PhonebookApp Class Methods: closeAllConnections() void closeAllConnections() { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(this.getClass().getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } 14
  • 15.
    Compile and Run PhonebookApp • compile - javac PhonebookApp.java • run - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp list - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp add myFirstName myLastName myEmail myMobile - java -cp .:lib/mysql-connector-java-5.1.34-bin.jar PhonebookApp delete 2 15
  • 16.
    Read The F*Manual • RTFM - https://dev.mysql.com/doc/ - http://docs.oracle.com/javase/ • Java: The Really Big Index - http://docs.oracle.com/javase/tutorial/reallybigindex.html • MySQL Help - mysql> HELP; - mysql> HELP CONTENTS; - mysql> HELP SELECT; 16
  • 17.