DAO comienzo

public class ActorDAO {
	private Connection con;

	public ActorDAO() {
		try {
			// Registrar el driver mysql
			Class.forName("com.mysql.cj.jdbc.Driver");
			// Conectarme a la base de datos
			 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public ArrayList<Actor> getActorAll() {
		try {
			String sql="select * from actor";
			PreparedStatement psmt=con.prepareStatement(sql);
			ResultSet res=psmt.executeQuery();
			ArrayList<Actor> actores= new ArrayList<Actor>();
			while (res.next()) {
				actores.add( new Actor(res.getInt("actor_id"),
						res.getString("first_name"),
						res.getString("last_name")));
			}
			return actores;
		}catch(Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public Actor getActor(int id) {
		try {
			String sql="select * from actor where actor_id=?";
			PreparedStatement psmt=con.prepareStatement(sql);
			psmt.setInt(1, id);
			ResultSet res=psmt.executeQuery();
			if (res.next()) {
				return new Actor(res.getInt("actor_id"),
						res.getString("first_name"),
						res.getString("last_name"));
			}
			else {
				return null;
			}
		}catch(Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	public boolean addActor(String first_name, String last_name) {
		try {
			String sql="insert into actor (first_name,last_name) values (?,?)";
			PreparedStatement psmt=con.prepareStatement(sql);
			psmt.setString(1, first_name);
			psmt.setString(2, last_name);
			int res=psmt.executeUpdate();
			return res==1;
		}catch(Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	public boolean addActor(Actor actor) {
		try {
			String sql="insert into actor (first_name,last_name) values (?,?)";
			PreparedStatement psmt=con.prepareStatement(sql);
			psmt.setString(1, actor.getFirst_name());
			psmt.setString(2, actor.getLast_name());
			int res=psmt.executeUpdate();
			return res==1;
		}catch(Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}

}
	public static void main(String[] args) {
		try {
			// El objeto DAO que me permite trabajar con la BD
			ActorDAO dao=new ActorDAO();
			// Utilizar  una de las propiedades: add
			for(int i=0;i<10000;i++) {
				dao.addActor("John"+i, "Travolta");
			}
			//dao.addActor("John", "Travolta");
			
			Actor eva=new Actor(0,"Eva","Wuig");
		//	dao.addActor(eva);
			
			System.out.println(dao.getActor(1));
			System.out.println(dao.getActorAll());
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos