1、导入druid包,然后进行加载
2、pom.xml中加载依赖 (使用哪种模块需要在导入对应依赖)
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
3、druid.properties:文件配置
jdbcUrl = jdbc:postgresql://172.16.5.102:5432/postgres?currentSchema=jdbcuser
username = jdbcuser
password = GBase_123
initialSize = 5
maxActive = 20
minIdle = 5
maxWait = 3000
4、java链接样例:(通过ddl、dml、dql执行)
package com.example.demo_druid; import com.alibaba.druid.pool.DruidDataSource; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; import java.sql.ResultSet; public class DruidTest { public static void main(String[] args) throws IOException, SQLException { //1.创建连接池 //1.加载配置文件 Properties pro = new Properties(); ResultSet rs=null; pro.load(DruidTest.class.getClassLoader().getResourceAsStream("druid.properties")); //2.创建数据源对象 /*DataSource:是SUN公司声明的接口 。DruidDataSource:是阿里巴巴对应实现的类*/ DataSource dataSource = new DruidDataSource(); //3.设置属性 DruidDataSource ds = (DruidDataSource)dataSource; ds.setUrl(pro.getProperty("jdbcUrl")); ds.setUsername(pro.getProperty("username")); ds.setPassword(pro.getProperty("password")); ds.setInitialSize(new Integer(pro.getProperty("initialSize"))); ds.setMaxActive(new Integer(pro.getProperty("maxActive"))); ds.setMinIdle(new Integer(pro.getProperty("minIdle"))); ds.setMaxWait(new Long(pro.getProperty("maxWait"))); //4.拿连接。直接通过数据源获取可用的连接 Connection conn = ds.getConnection(); System.out.println(conn);//检验是否能够成功拿到一个数据库连接池中的连接 //2.编写sql语句 String sql1 = "create table aaaa(a int,b varchar(20))"; String sql = "insert into aaaa values (2,'druiftest')"; String sql2 = "select * from v_userrole limit 10"; String sql3 = "select * from users"; //3.PreparedStatement PreparedStatement pst = conn.prepareStatement(sql1); //System.out.println(pst); //4.执行sql pst.executeUpdate(); //pst.executeUpdate(); //rs=pst.executeQuery(); while (rs.next()){ //判断是否有数据 //有数据便获取数据然后输出 String userid=rs.getString("username"); String useralias=rs.getString("password"); String roleid=rs.getString("enabled"); System.out.println(userid+"|"+" "+useralias+" |"+roleid); } //5.直接关闭资源即可, conn.close(); pst.close(); } }