SlideShare a Scribd company logo
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

More Related Content

PDF
Java Cheat Sheet
PDF
Scala jeff
PDF
JavaScript Fundamentals with Angular and Lodash
PPTX
Slick: Bringing Scala’s Powerful Features to Your Database Access
PDF
Brief introduction of Slick
PDF
Why Haskell
PDF
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
PPTX
Java and XML Schema
Java Cheat Sheet
Scala jeff
JavaScript Fundamentals with Angular and Lodash
Slick: Bringing Scala’s Powerful Features to Your Database Access
Brief introduction of Slick
Why Haskell
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Java and XML Schema

What's hot (20)

PDF
Scala vs Java 8 in a Java 8 World
PDF
Functional Algebra: Monoids Applied
PPTX
Js types
KEY
Indexing thousands of writes per second with redis
PDF
Swift, functional programming, and the future of Objective-C
PDF
Introduction To Scala
PPT
Scala presentation by Aleksandar Prokopec
PDF
Introduction to Python
PDF
Java7 New Features and Code Examples
PDF
Haskell in the Real World
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PPTX
Java and XML
PDF
Hacking XPATH 2.0
PDF
Swift for TensorFlow - CoreML Personalization
PDF
Ruby tricks2
PPT
XML - State of the Art
PPTX
Cassandra 2.2 & 3.0
PDF
PHP Static Code Review
PPT
Sql
PPTX
Django and working with large database tables
Scala vs Java 8 in a Java 8 World
Functional Algebra: Monoids Applied
Js types
Indexing thousands of writes per second with redis
Swift, functional programming, and the future of Objective-C
Introduction To Scala
Scala presentation by Aleksandar Prokopec
Introduction to Python
Java7 New Features and Code Examples
Haskell in the Real World
Java OOP Programming language (Part 8) - Java Database JDBC
Java and XML
Hacking XPATH 2.0
Swift for TensorFlow - CoreML Personalization
Ruby tricks2
XML - State of the Art
Cassandra 2.2 & 3.0
PHP Static Code Review
Sql
Django and working with large database tables
Ad

Viewers also liked (10)

PDF
Java for beginners
PDF
MySQL Cheat Sheet
PDF
Java Cheat Sheet
PDF
Cheat sheet - String Java (Referência rápida)
PDF
Cheat Sheet java
PDF
Web Components Revolution
PDF
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
PDF
24 Books You've Never Heard Of - But Will Change Your Life
PDF
20 Quotes To Turn Your Obstacles Into Opportunities
PDF
Work Rules!
Java for beginners
MySQL Cheat Sheet
Java Cheat Sheet
Cheat sheet - String Java (Referência rápida)
Cheat Sheet java
Web Components Revolution
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
24 Books You've Never Heard Of - But Will Change Your Life
20 Quotes To Turn Your Obstacles Into Opportunities
Work Rules!
Ad

Similar to Developing Applications with MySQL and Java for beginners (20)

DOCX
Week 12 code
PPT
JDBC Tutorial
PPT
3 database-jdbc(1)
PPT
JDBC Connecticity.ppt
PPT
General Principles of Web Security
PDF
JS Fest 2019 Node.js Antipatterns
PPTX
Django - sql alchemy - jquery
PDF
Migrating legacy data
PDF
Unit testing with zend framework tek11
KEY
Unit testing zend framework apps
PDF
Charla EHU Noviembre 2014 - Desarrollo Web
PPTX
Nodejs do teste de unidade ao de integração
DOCX
My java file
PDF
Simpan data- ke- database
PDF
OWASP Top 10 - DrupalCon Amsterdam 2019
PPT
PHP - Getting good with MySQL part II
KEY
Unit testing with zend framework PHPBenelux
PDF
Php summary
PDF
Tomcat连接池配置方法V2.1
PDF
My app is secure... I think
Week 12 code
JDBC Tutorial
3 database-jdbc(1)
JDBC Connecticity.ppt
General Principles of Web Security
JS Fest 2019 Node.js Antipatterns
Django - sql alchemy - jquery
Migrating legacy data
Unit testing with zend framework tek11
Unit testing zend framework apps
Charla EHU Noviembre 2014 - Desarrollo Web
Nodejs do teste de unidade ao de integração
My java file
Simpan data- ke- database
OWASP Top 10 - DrupalCon Amsterdam 2019
PHP - Getting good with MySQL part II
Unit testing with zend framework PHPBenelux
Php summary
Tomcat连接池配置方法V2.1
My app is secure... I think

More from Saeid Zebardast (9)

PDF
Introduction to Redis
PDF
An Introduction to Apache Cassandra
PDF
An overview of Scalable Web Application Front-end
PDF
MySQL for beginners
PDF
هفده اصل افراد موثر در تیم
PDF
What is good design?
PDF
How to be different?
PDF
What is REST?
PDF
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد
Introduction to Redis
An Introduction to Apache Cassandra
An overview of Scalable Web Application Front-end
MySQL for beginners
هفده اصل افراد موثر در تیم
What is good design?
How to be different?
What is REST?
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PPTX
Big Data Technologies - Introduction.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Electronic commerce courselecture one. Pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
Cloud computing and distributed systems.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Machine learning based COVID-19 study performance prediction
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Empathic Computing: Creating Shared Understanding
Big Data Technologies - Introduction.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Electronic commerce courselecture one. Pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Advanced methodologies resolving dimensionality complications for autism neur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Cloud computing and distributed systems.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Network Security Unit 5.pdf for BCA BBA.
Encapsulation_ Review paper, used for researhc scholars
NewMind AI Monthly Chronicles - July 2025
Machine learning based COVID-19 study performance prediction
20250228 LYD VKU AI Blended-Learning.pptx

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