【JDBC-Druid-JdbcTemplate】使用JdbcTemplate(通过Druid连接池)的方式操作数据库

1)导入依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <!--<scope>test</scope>-->
</dependency>

2)定义JdbcUtils工具类

2.1.定义工具类获取DruidDataSource

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DruidDataSource dataSource;
	//获取DruidDataSource 
    public static DruidDataSource getDataSource() {
        dataSource = new DruidDataSource();
        dataSource.setInitialSize(1);
        dataSource.setMaxActive(2);
        dataSource.setMaxWait(3000);
        return dataSource;
    }
	
	//通过getDataSource()获取到的dataSource来创建JDBC连接信息
	//传参的方式获取连接
    public static JdbcTemplate sourceJdbcTemplate(String url, String username, String password) {
        DruidDataSource dataSource = getDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return new JdbcTemplate(dataSource);
    }

	//通过getDataSource()获取到的dataSource来创建JDBC连接信息
	//写死的方式获取连接
    public static JdbcTemplate mysqlJdbcTemplate() {
        DruidDataSource dataSource = getDataSource();
        dataSource.setUrl(Config.mysqlUrl);
        dataSource.setUsername(Config.mysqlUsername);
        dataSource.setPassword(Config.mysqlPassword);
        return new JdbcTemplate(dataSource);
    }

	//通过properties配置文件的方式获取连接
    public static DataSource getDataSourceFactory() {
        Properties properties = new Properties();
        try {
        properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            try {
                dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataSource;
    }
	
	//通过properties配置文件的方式获取连接,需要释放资源
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

2.2.配置druid.properties

注意

如果平时只需要连接一个数据库不需要对数据库进行频繁切换的情况下,那么可以通过properties配置文件的方式获取数据库连接,方法为上面的getDataSourceFactory(),但是需要配置druid.properties

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.1:3306/test
username=root
password=123456
initialSize=1
maxActive=2
maxWait=3000

3)通过定义好的JdbcUtils工具类使用JdbcTemplate(Druid连接池)

使用Junit进行测试(下面只是样例,无法正常执行,仅供参考):

public class Demo {
    private static DataSource dataSource;
    private static JdbcTemplate jdbcTemplate;
    private static Connection conn;
    private static PreparedStatement ps;
    private static ResultSet rs;

    @Test
    public void test1() {
        DataSource dataSourceFactory = JdbcUtils.getDataSourceFactory();
        try {
            conn = dataSourceFactory.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                int a = rs.getInt(1);
                int b = rs.getInt(2);
                int c = rs.getInt(3);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn, ps, rs);
        }
    }
    
	@Test
	//JdbcTemplate.queryForList(sql,返回类型.class)直接返回一个List集合
	public void test2(String httpUrl, String username, String password, String sourceDatabase, String likeTable) {
        String sql = null;
        jdbcTemplate = JdbcUtils.sourceJdbcTemplate(httpUrl, username, password);
        if (likeTable == null || "".equals(likeTable)) {
            sql = "SELECT lower(table_name) FROM information_schema.tables where table_schema = '" + sourceDatabase + "' and table_type != 'VIEW';";
        } else {
            sql = "SELECT lower(table_name) FROM information_schema.tables where table_schema = '" + sourceDatabase + "' and table_name like '" + likeTable + "' and table_type != 'VIEW';";
        }
        return jdbcTemplate.queryForList(sql, String.class);
    }

	@Test
	//JdbcTemplate.query(sql,new RowMapper(返回的数据类型,可以为bean类型))直接返回一个List集合
	//如果循环执行JdbcTemplate.query(),那么每次循环都会返回一个List1,需要外部定义一个List2,使用List2.addAll(List1)的方式对每次循环产生的List1进行收集。
    public void test3(String httpUrl, String username, String password, String sourceDatabase, List<String> mysqlLackTables, int dataSourceInfoId, String sourceName) {
        List<TableComment> tableComments = new ArrayList<>();
        jdbcTemplate = JdbcUtils.sourceJdbcTemplate(httpUrl, username, password);
        String sql = "SELECT lower(TABLE_NAME), TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '" + sourceDatabase + "' and lower(TABLE_NAME) = lower('%s')";
        for (String mysqlLackTable : mysqlLackTables) {
            tableComments.addAll(jdbcTemplate.query(String.format(sql, mysqlLackTable), new RowMapper<TableComment>() {
                @Override
                public TableComment mapRow(ResultSet rs, int i) throws SQLException {
                    TableComment tableComment = new TableComment();
                    tableComment.setTableName(rs.getString(1));
                    tableComment.setTableComment(rs.getString(2));
                    return tableComment;
                }
            }));
        }
    }
    
	@Test
	//JdbcTemplate.update(sql)对数据进行更新,写入,删除操作
	public void test4(List<TableComment> list, int dataSourceInfoId, String sourceName) {
        jdbcTemplate = JdbcUtils.mysqlJdbcTemplate();
        String sql = "insert into `data_resource_table_info` (s_table_name,s_table_name_zh,d_table_name,d_table_name_zh,approve_sts,data_source_id,data_source_name,sts,sts_date,create_user_id,create_time,update_user_id,update_time,remarks) values('%s','%s','%s','%s','C'," + dataSourceInfoId + ",'" + sourceName + "','A',NOW(),1,NOW(),1,NOW(),null)";
        list.stream().forEach(tableComment -> {
            String tableName = tableComment.getTableName();
            String comment = tableComment.getTableComment();
            jdbcTemplate.update(String.format(sql, tableName, comment, tableName, comment));
        });
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要获取`application-druid.yml`中的连接对象,需要使用Druid数据源。Druid是阿里巴巴开发的JDBC连接池,具有监控、防御SQL注入攻击和并发控制等特性。 以下是获取`application-druid.yml`的连接对象的示例代码: ```java import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @EnableConfigurationProperties(DatabaseProperties.class) public class DataSourceConfig { @Autowired private DatabaseProperties properties; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(properties.getUrl()); dataSource.setUsername(properties.getUsername()); dataSource.setPassword(properties.getPassword()); // 设置其他属性,例如连接池大小、连接超时等 return dataSource; } } ``` 在上面的示例中,`@EnableConfigurationProperties`注解用于启用`DatabaseProperties`类,`@Autowired`注解则将`DatabaseProperties`类注入到`DataSourceConfig`类中。`dataSource()`方法用于创建一个`DruidDataSource`对象,并设置连接信息,最后将其返回。可以在方法中设置其他的属性,例如最大连接数、最小连接数、连接超时时间等。需要注意的是,`dataSource()`方法需要使用`@Bean`注解,以便Spring容器可以自动注入数据源。 在使用连接对象时,只需将`DataSource`对象注入到需要连接数据库的代码中即可。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class MyDao { private final JdbcTemplate jdbcTemplate; @Autowired public MyDao(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } // 使用jdbcTemplate执行SQL语句 } ``` 在上面的示例中,`MyDao`类中包含一个`jdbcTemplate`对象,它通过构造函数注入了`DataSource`对象,以便可以使用`jdbcTemplate`对象执行SQL语句。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值