JDBC // 1,加载驱动 Class.forName(“com.mysql.jdbc.Driver”); // 2,得到链接 String url = “jdbc:mysql://localhost:3306/person?useUnicode=true&characterEncoding=utf-8”; String user = “root”; String password = “root”; con = DriverManager.getConnection(url,user,password); //3,创建状态 st = con.createStatement(); //4,得到结果集 String sql = “select nameid,name from emp”; rs = st.executeQuery(sql); //5,处理结果 while (rs.next()){ int id = rs.getInt(“nameid”); String name = rs.getString(“name”); System.out.println(id+"\t"+name); } } catch (Exception e) { e.printStackTrace(); }finally { //6,释放资源 try { rs.close(); st.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); }
JNDI 连接池配置: 1,连接池单例化,
public class DB { private DB(){}; private static DB db = null; public static DB getInstance(){ if (db == null){ db = new DB(); } return db; } Connection con; public Connection getConnect() throws Exception { Context c = new InitialContext(); DataSource ds = (DataSource) c.lookup(“java:comp/env/news”); con = ds.getConnection(); return con; } }
将连接池放入一个单例中
2,项目中Web配置 news javax.sql.DataSource Container
3,Tomcat中context。xml文件配置
三步配置中 1 中的lookup后的“news” 2 中的中的“news” 3 中的name=“news” 三部分必须一致,
3 中的 auth=“Container” 2 中的中的“Container” 必须一致