mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-05-14 23:24:46 +00:00
Upload of pre-existing files
This commit is contained in:
commit
4c21152830
150 changed files with 730703 additions and 0 deletions
115
Java/DAO.md
Normal file
115
Java/DAO.md
Normal file
|
@ -0,0 +1,115 @@
|
|||
# Database Access Object
|
||||
|
||||
## DB
|
||||
|
||||
Connection to the DB.
|
||||
|
||||
```java
|
||||
package dao;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DB {
|
||||
|
||||
private Connection conn; // db connection obj
|
||||
|
||||
private final String URL = "jdbc:<dbms>:<db_url>/<database>";
|
||||
private final String USER = "";
|
||||
private final String PWD = "";
|
||||
|
||||
public DB() {
|
||||
this.conn = null;
|
||||
}
|
||||
|
||||
public void connect() {
|
||||
try {
|
||||
this.conn = DriverManager.getConnection(URL, USER, PWD);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if(conn != null) {
|
||||
try {
|
||||
this.conn.close();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Connection getConn() {
|
||||
return conn;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `I<Type>DAO`
|
||||
|
||||
Interface for CRUD methods on a database.
|
||||
|
||||
```java
|
||||
package dao;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public interface I<Type>DAO {
|
||||
|
||||
String RAW_QUERY = "SELECT * ..."
|
||||
public Type Query() throws SQLException;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## `<Type>DAO`
|
||||
|
||||
Class implementing `I<Type>DAO` and handling the comunication with the db.
|
||||
|
||||
```java
|
||||
package dao;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class <Type>DAO implements I<Type>DAO {
|
||||
|
||||
private <Type> results;
|
||||
|
||||
private Statement statement; // SQL instruction contenitor
|
||||
private ResultSet rs; // Query results contenitor
|
||||
private DB db;
|
||||
|
||||
public <Type>DAO() {
|
||||
db = new DB();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type Query() throws SQLException {
|
||||
// 1. connection
|
||||
db.connect();
|
||||
|
||||
// 2. instruction
|
||||
statement = db.getConn().createStatement(); // statement creation
|
||||
|
||||
// 3. query
|
||||
rs = statement.executeQuery(RAW_QUERY); // set the query
|
||||
|
||||
// 4. results
|
||||
while(rs.next()) {
|
||||
// create and valorize Obj
|
||||
// add to results
|
||||
}
|
||||
|
||||
// 5. disconnection
|
||||
db.disconnect()
|
||||
|
||||
// 6. return results
|
||||
return results;
|
||||
}
|
||||
}
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue