项目作者: fefong

项目描述 :
Application Java with MySQL (CRUD);
高级语言: Java
项目地址: git://github.com/fefong/java_mysql_crud.git
创建时间: 2019-10-06T19:03:08Z
项目社区:https://github.com/fefong/java_mysql_crud

开源协议:

下载


Java CRUD with MySQL

Example Java using MySQL

  • CRUD
    • C - CREATE
    • R - READ
    • U - UPDATE
    • D - DELETE

Model

Model: Person;

  1. public class Person {
  2. private int id;
  3. private String name;
  4. private Date date;
  5. //Getters and Setters
  6. }

MySQL

  • MySQL
    • Database;
    • Tables;
    • Procedures;
    • Views;
  • mysql-script: script.sql

Driver JDBC

Driver MySQL: mysql-connector 5.1.15

DAO

Imports

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;

Variables

  1. Connection cn;
  2. private final String driver = "com.mysql.jdbc.Driver";
  3. final String userDB = "root";
  4. final String passwordDB = "";
  5. final String databaseDB = "database_test";
  6. private static final String ip = "localhost";
  7. private static final String port = "3307";
  8. private final String url = "jdbc:mysql://" + ip + ":" + port + "/";
  9. ResultSet rs = null;
  10. Statement st = null;
  11. PreparedStatement ps = null;
  12. CallableStatement stmt = null;

Constants

  1. static final String PROCEDURE_INSERT_PERSON = "{ call stp_insert_person (?, ? ) }";
  2. static final String PROCEDURE_UPDATE_PERSON = "{ call stp_update_person (?, ?, ? ) }";
  3. static final String PROCEDURE_DELETE_PERSON = "{ call stp_delete_person (? ) }";
  4. static final String VIEW_PERSON = "SELECT * FROM view_person";
  5. static private final String COLUMN_ID = "id_person";
  6. static private final String COLUMN_NAME = "name_person";
  7. static private final String COLUMN_DATE = "date_person";

Methods

:warning: Need add throws declaration or surround with try/catch;

:warning: It is recommended to use procedures for insert, update and delete and view/procedures for selects;

Method - Connect database

  1. Class.forName(driver);
  2. cn = DriverManager.getConnection(String url,String user, String password);

Method - Disconnect database

  1. cn.close();

Procedure

How to call procedure.

Procedure implemented: PersonDAO

Check connection

  1. if (conect()) {
  2. // TODO
  3. }

Procedure implementation

  1. CallableStatement cstmt = cn.prepareCall(PROCEDURE_DELETE_PERSON);
  2. cstmt.setInt(1, id);
  3. cstmt.execute();

View

How to select VIEW.

View implemented: PersonDAO;

List

  1. List<Person> persons = new ArrayList<Person>();

View implementation

  1. st = cn.createStatement();
  2. rs = st.executeQuery(VIEW_PERSON);
  3. while (rs.next()) {
  4. persons.add(
  5. new Person(
  6. rs.getInt(COLUMN_ID),
  7. rs.getString(COLUMN_NAME),
  8. rs.getDate(COLUMN_DATE)
  9. )
  10. );
  11. }

Exception

  • SQLException;
  • ClassNotFoundException;

Project

Download: Java MySQL - CRUD