上面是展示的数据库
接下来是JDBC工具类
public class JDBCutils { public static void main(String[] args) throws Exception { //3.加载配置文件 Properties pro = new Properties(); InputStream id = JDBCutils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(id); //4.获取连接池对象 DataSource ds = DruidDataSourceFactory.createDataSource(pro); //5.获取连接 Connection conn = ds.getConnection(); System.out.println(conn); } //定义成员变量 private static DataSource ds; static { try { //1.加载配置文件 Properties pro = new Properties(); pro.load(JDBCutils.class.getClassLoader().getResourceAsStream("druid.properties")); //2.获取dataSource ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); } //释放资源 public static void close(Statement stmt, Connection conn){ close(null,stmt,conn); } public static void close(ResultSet rs, Statement stmt, Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); //归还连接 } catch (SQLException e) { e.printStackTrace(); } } } }
这是连接成功代码 用的是durid数据库连接池
这是JDBCutils工具类连接池测试类
这是链接数据库成功的代码
这是数据库交互成功代码
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/student?serverTimezone = UTC username=root password=123456 # 初始化连接数量 initialSize=5 # 最大连接数量 maxActive=10 # 最大等待时间 maxWait=3000 validationQuery:SELECT 1 testWhileIdle:true testOnBorrow:false testOnReturn:falsez
这是durid配置文件
一定要将durid.propreties文件放置在resource文件夹中
将JDBC和Servlet放在一起学习是很难的· 特别是JDBC交互不上数据库 servlet交互不上tomcat
学编程 就要一个问题一个问题去解决 以上代码亲测有效 !!!!