Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package persistence.db;
- import business_logic.Address;
- import business_logic.EMail;
- import business_logic.MainInterface;
- import business_logic.Telephone;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public abstract class DAO<T extends MainInterface>{
- private Connection connection;
- public DAO(Connection connection){
- this.connection = connection;
- }
- public Connection getConnection(){
- return connection;
- }
- public void closeAll(ResultSet rs, PreparedStatement pstmt){
- try{
- if(pstmt != null)
- pstmt.close();
- if(rs != null)
- rs.close();
- }catch(SQLException sqle){}
- }
- public long getModified(String table, int id){
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try{
- pstmt = connection.prepareStatement("SELECT modified FROM "+table+" WHERE id = ?");
- pstmt.setInt(1, id);
- rs = pstmt.executeQuery();
- if(rs.next())
- return rs.getLong("modified");
- else
- return 0;
- }catch(SQLException ex){
- Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
- }finally{
- closeAll(rs, pstmt);
- }
- return 0;
- }
- public long getCurrentTimestamp(){
- return System.currentTimeMillis()/1000;
- }
- public void setId(PreparedStatement pstmt, T a){
- try{
- ResultSet keys = pstmt.getGeneratedKeys();
- if (keys.next())
- a.setId(keys.getInt(1));
- keys.close();
- }catch(SQLException ex){
- Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- package test;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import persistence.db.*;
- import business_logic.*;
- public class AddressDaoTest{
- private static Connection connection;
- private static AddressDAO dao;
- public static void main(String args[]){
- try{
- Class.forName("com.mysql.jdbc.Driver");
- }catch(ClassNotFoundException ex){
- Logger.getLogger(MySQL.class.getName()).log(Level.SEVERE, null, ex);
- }
- try{
- connection = DriverManager.getConnection("jdbc:mysql://localhost/schoolmanagement", "root", "");
- }catch(SQLException ex){
- Logger.getLogger(MySQL.class.getName()).log(Level.SEVERE, null, ex);
- }
- dao = new AddressDAO(connection);
- Address ad = null;
- try{
- ad = new Address(0, 1, 0, 0, "Teststreet", "Testhnr", "1234", "Testcity");
- }catch(SchulException ex){
- Logger.getLogger(AddressDaoTest.class.getName()).log(Level.SEVERE, null, ex);
- }
- System.out.println("ID: "+ad.getId());///getId liefert 0, da dem Konstruktor 0 übergeben wird
- dao.save(ad);
- System.out.println("ID: "+ad.getId());//getId liefert immer noch 0
- }
- }
Add Comment
Please, Sign In to add comment