DAO de city

package com.trifulcas.DAO;

public class City {
	private int city_id;
	private int country_id;
	private Country country;
	private String city;
	
	public City(int city_id, int country_id, String city) {
		super();
		this.city_id = city_id;
		this.country_id = country_id;
		this.city = city;
	}
	public int getCity_id() {
		return city_id;
	}
	public void setCity_id(int city_id) {
		this.city_id = city_id;
	}
	public int getCountry_id() {
		return country_id;
	}
	public void setCountry_id(int country_id) {
		this.country_id = country_id;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Country getCountry() {
		return country;
	}
	public void setCountry(Country country) {
		this.country = country;
	}
	@Override
	public String toString() {
		return "City [city_id=" + city_id + ", country_id=" + country_id + ", country=" + country + ", city=" + city
				+ "]";
	}
	
	
	
}
package com.trifulcas.DAO;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// En esta clase vamos a implementar la lógica del CRUD
// Desde aquí accederemos a la base de datos
public class CityDAO {
	// Tenemos una variable para almacenar la conexión
	private Connection con;
	private PreparedStatement st;
	private ResultSet rs;
	private CountryDAO countryDAO;
	
	public CityDAO() {
		this("sakila");
	}

	public CityDAO(String bd) {
		try {
			// Nos conectamos en el constructor, la variable con estará disponible
			// para todas las funciones de la clase DAO
			Class.forName("com.mysql.cj.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + bd, "root", "");
			countryDAO=new CountryDAO();
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

	public void close() {
		try {
			con.close();
			st.close();
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// cRud
	// Obtengo un pais por el ID
	public City getCity(int id) {
		try {
			// Lo hago igual que hasta ahora, SQL, STATEMENT, RESULTSET
			String sql = "select * from city where city_id=?";
			st = con.prepareStatement(sql);
			st.setInt(1, id);
			rs = st.executeQuery();
			// Si hay resultado construyo un país con los datos que me devuelve la consulta
			if (rs.next()) {
				City ciudad= new City(rs.getInt("city_id"),rs.getInt("country_id"), rs.getString("city"));
				Country pais=countryDAO.getCountry(ciudad.getCountry_id());
				ciudad.setCountry(pais);
				return ciudad;
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return null;
	}

	
}
package com.trifulcas.DAO;

public class TestCiy {

	public static void main(String[] args) {
		CityDAO cityDAO=new CityDAO();
		
		City ciudad=cityDAO.getCity(1);
		
		System.out.println(ciudad);

	}

}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos