SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML SchemaRaji Ghawi
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redispauldix
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaPeter Maas
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real Worldosfameron
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
XML - State of the Art
XML - State of the ArtXML - State of the Art
XML - State of the ArtJakub Malý
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
 

Mais procurados (20)

Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Js types
Js typesJs types
Js types
 
Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redis
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Java and XML
Java and XMLJava and XML
Java and XML
 
Hacking XPATH 2.0
Hacking XPATH 2.0Hacking XPATH 2.0
Hacking XPATH 2.0
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
XML - State of the Art
XML - State of the ArtXML - State of the Art
XML - State of the Art
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
Sql
SqlSql
Sql
 

Destaque

Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat SheetGlowTouch
 
Cheat sheet - String Java (Referência rápida)
Cheat sheet - String Java (Referência rápida)Cheat sheet - String Java (Referência rápida)
Cheat sheet - String Java (Referência rápida)Rafael Liberato
 
Web Components Revolution
Web Components RevolutionWeb Components Revolution
Web Components RevolutionSaeid Zebardast
 
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!Noopur Gupta
 
24 Books You've Never Heard Of - But Will Change Your Life
24 Books You've Never Heard Of - But Will Change Your Life24 Books You've Never Heard Of - But Will Change Your Life
24 Books You've Never Heard Of - But Will Change Your LifeRyan Holiday
 
20 Quotes To Turn Your Obstacles Into Opportunities
20 Quotes To Turn Your Obstacles Into Opportunities20 Quotes To Turn Your Obstacles Into Opportunities
20 Quotes To Turn Your Obstacles Into OpportunitiesRyan Holiday
 

Destaque (10)

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

Semelhante a Developing Applications with MySQL and Java for beginners

JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.pptSwapnil Kale
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsTimur Shemsedinov
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebMikel Torres Ugarte
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integraçãoVinícius Pretto da Silva
 
Simpan data- ke- database
Simpan data- ke- databaseSimpan data- ke- database
Simpan data- ke- databaseTri Sugihartono
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019Ayesh Karunaratne
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part IIFirdaus Adib
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 

Semelhante a Developing Applications with MySQL and Java for beginners (20)

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

Mais de Saeid Zebardast

An Introduction to Apache Cassandra
An Introduction to Apache CassandraAn Introduction to Apache Cassandra
An Introduction to Apache CassandraSaeid Zebardast
 
An overview of Scalable Web Application Front-end
An overview of Scalable Web Application Front-endAn overview of Scalable Web Application Front-end
An overview of Scalable Web Application Front-endSaeid Zebardast
 
هفده اصل افراد موثر در تیم
هفده اصل افراد موثر در تیمهفده اصل افراد موثر در تیم
هفده اصل افراد موثر در تیمSaeid Zebardast
 
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزادمعرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزادSaeid Zebardast
 

Mais de Saeid Zebardast (9)

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

Último

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Último (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.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