11. 对象与关系的映射(利用反射) [java] public class ORMTest { /** * @param args * @throwsInvocationTargetException * @throwsIllegalAccessException * @throws SQLException * @throwsIllegalArgumentException * @throws InstantiationException */ public static void main(String[] args) throws IllegalArgumentException, SQLException, IllegalAccessException,InvocationTargetException, InstantiationException { User user = (User) getObject( "select idas Id ,name as Name, birthday as Birthday,money as Money from user whereid=2", User.class); System.out.println(user); } static ObjectgetObject(String sql, Class clazz) throws SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); ps = conn.prepareStatement(sql); rs = ps.executeQuery();
12. 创建数据库连接池,先创建多个连接,将连接一次放在List的尾部,用的时候从List的头部取出连接,使用连接;用完释放连接的时候是将连接返回到连接池的尾部,供后边的用户使用。达到连接重复使用的目地。 [java] /** * * 创建数据库连接池 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.LinkedList; public class MyDataSource { private static String url = "jdbc:mysql://localhost:3306/jdbc"; private static String user = "root"; private static String password = "mysql"; private LinkedListconnectionsPoll = new LinkedList(); public MyDataSource(){ for(int i = 0; i<5;i++){ try { this.conn