1. 程式人生 > >jdbc 查詢全部

jdbc 查詢全部

man exc ddr sta get 聲明 oca nec dao

public ArrayList getAllPersons()
{
ArrayList arrPersons = new ArrayList();
Connection conn = null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/persondb", "root", "root");
String sql = "select * from t_person";
PreparedStatement psmt = conn.prepareStatement(sql);
ResultSet rs = psmt.executeQuery();
while(rs.next())
{
String pid = rs.getString(1);
String pname = rs.getString(2);
int age = rs.getInt(3);
float height = rs.getFloat(4);
float weight = rs.getFloat(5);
String address = rs.getString(6);
Person person = new Person(pid, pname, age, height, weight, address);
arrPersons.add(person);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arrPersons;
}

//調用

//1.聲明一個要加入的PERSON對象
Person tom = new Person("p02", "jack", 21, 185, 65, "USA");
//2.聲明一個要操作的類對象
PersonDAOImpl personDAO = new PersonDAOImpl();
//3.對象調用查詢方法
ArrayList arrayPerson = personDAO.getAllPersons();
for (int i = 0; i < arrayPerson.size(); i++) {
Person person = (Person)arrayPerson.get(i);
System.out.println(person);
}

jdbc 查詢全部