ResultSetHandler h = new KeyedHandler("id");
Map found = (Map) queryRunner.query("select id, name, age from person", h);
Map jane = (Map) found.get(new Long(1)); // jane's id is 1
String janesName = (String) jane.get("name");
Integer janesAge = (Integer) jane.get("age");
@Override
public Long save(String sql) {
Long id = null;
String ins_sql = "INSERT INTO person (NAME, age, address) VALUES ('aaa', 21, 'address001')";
Connection conn = DBToolkit.getConnection();
QueryRunner qr = new QueryRunner();
try {
qr.update(conn, ins_sql);
//获取新增记录的自增主键
id = (Long) qr.query(conn, "SELECT LAST_INSERT_ID()",new ScalarHandler(1));
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection(conn);
}
return id;
}
@Override
public int delete(Long id) {
int x = 0;
Connection conn = DBToolkit.getConnection();
QueryRunner qr = new QueryRunner();
try {
x = qr.update(conn, "DELETE FROM person WHERE id = ?", id);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection(conn);
}
return x;
}
@Override
public int update(Person person) {
int x = 0;
Connection conn = DBToolkit.getConnection();
QueryRunner qr = new QueryRunner();
try {
x = qr.update(conn, "UPDATE person SET NAME = ?, age = ?, address = ? WHERE id = ?","xxx", 23,"ttt", 5);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection(conn);
}
return x;
}
@Override
public Person load(Long id) {
Connection conn = DBToolkit.getConnection();
QueryRunner qr = new QueryRunner();
try {
Person person = (Person) qr.query(conn, "SELECT * FROM person where id = ?", new BeanHandler(Person.class), 3L);
System.out.println(person.getId() + "\t" + person.getSdf() + "\t" + person.getAge() +"\t" + person.getAddress());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Person> findPerson(String sql) {
Connection conn = DBToolkit.getConnection();
QueryRunner qr = new QueryRunner();
try {
List<Person> pset = (List) qr.query(conn, "SELECT * FROM person", new BeanListHandler(Person.class));
for (Person person : pset) {
System.out.println(person.getId() + "\t" + person.getSdf() + "\t" + person.getAge() +"\t" + person.getAddress());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Person load4Map(Long id) {
Connection conn = DBToolkit.getConnection();
QueryRunner qr = new QueryRunner();
try {
//先将两个字段置为null
qr.update(conn, "update person set age =null,address =null where id =1");
Map<String, Object> map = qr.query(conn, "SELECT * FROM person where id = ?", new MapHandler(), 1L);
Person person = new Person();
person.setId((Long) map.get("id"));
person.setSdf((String) map.get("name"));
person.setAge((Integer) map.get("age"));
person.setAddress((String) map.get("address"));
System.out.println(person.getId() + "\t" + person.getSdf() + "\t" + person.getAge() +"\t" + person.getAddress());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}