目录
jdbc取出来的是记录集 resultSet,遍历(同时取字段)
取出来直接就是对象集合。配置(表book ----------实体类Book)
web开发
如果现在同时有 十万个浏览器在访问 网站,是不是就有 十万个连接Connection在内存中?
jdbc:报错?是否看到了执行的sql语句是什么?
增删改查
classpath:类的查找路径
web开发同时有10万个浏览器访问网站,就有10万个连接,内存就会被撑爆
- public class JDBCUtil {
- static Connection con = null;
- public static Connection getConnection(){
- if (con != null){
- return con;
- }
- else {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?user=root&password=123456");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- return con;
- }
- }
- }
- public class MyTest {
- public static void main(String[] args) throws Exception{
- Connection con = JDBCUtil.getConnection();
- Connection con2 = JDBCUtil.getConnection();
- System.out.println(con == con2); //false
- System.out.println(con);
- System.out.println(con2);
- }
- }
- 如何判断连接是否被关闭?
-
- try {
- if (con != null) {
- if (!con.isClosed()) {
- return con;
- } else {
- con = DriverManager.getConnection(URL,USER,PASSWORD);
- return con;
- }
- } else {
- con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?user=root&password=123456");
- return con;
- }
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- return con;
- }
维护——编写连接池类
- private static final String DIRVER = "com.mysql.jdbc.Driver";
- private static final String URL = "jdbc:mysql://localhost:3306/shop?";
- private static final String USER = "root";
- private static final String PASSWORD = "123456";
-
-
- static Connection[] cons; //10个,null
- static int count = 0;
- //静态代码块
- static {
- try {
- System.out.println("加载驱动");
- Class.forName(DIRVER);
-
- //准备10个连接
- cons = new Connection[10];
- for (int i = 0; i < cons.length; i++) {
- cons[i] = DriverManager.getConnection(URL,USER,PASSWORD);
- }
-
- } catch (ClassNotFoundException | SQLException e) {
- e.printStackTrace();
- }
-
- }
- public static Connection getConnection() {
- count = count % 10 ;
- return cons[count++];
-
- }
- Class DBPool implements DataSource{
- getConnection (){
-
- }
- }
- new ComboPooledDataSource();
-
-
-
- //use C3P0,数据源(连接池是数据源),ComboPooledDataSource()
- ComboPooledDataSource dataSource = new ComboPooledDataSource();
- dataSource.setDriverClass("com.mysql.jdbc.Driver");
- dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/shop");
- dataSource.setUser("root");
- dataSource.setPassword("123456");
-
- Connection con = dataSource.getConnection();
-
- Statement stmt = con.createStatement();
-
- ResultSet re = stmt.executeQuery("select * from book");
- while (re.next()){
- System.out.println(re.getString("name"));
- }