【Java】Springboot项目执行sql的方式

推荐使用jdbcTemplate

使用这个,不用手动关闭Statement Connection,很方便。

@Service("vTService")
public class VTServiceImpl{

    @Autowired
    @Qualifier("jdbcTemplate2") //有多个数据源的,需要名称区分
    private JdbcTemplate jdbcTemplate;

	public String createTable(String id) {
        String tableName = "tmp" + id;
        String sql = "CREATE TABLE \"public\".\"" + tableName + "\" (c integer, a integer, b integer, d bytea);" +
                "CREATE UNIQUE INDEX \"" + tableName + "_unique_zcr_idx\" on \"public\".\"" + tableName + "\" (c, a, b);";
        jdbcTemplate.execute(sql);
        return tableName;
    }
}

需要结果的

# 单个结果
Long id = jdbcTemplate.executeForObject("select id from tb where xxx = 'yyy'",Long.class);
# 多个结果
String sql = "select id from tb"; 
List<Long> ids = jdbcTemplate.executeForList(sql,Long.class);
# 结果集,类似ResultSet
SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);
while(sqlRowSet.next){
	long id = sqlRowSet.getLong(1)
}

映射自定义类

RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
String sql="select userName,userPwd from userinfo";
List<User> users=jt.query(sql,rowMapper);
for (User u:users) {
	System.out.println(u);
}
SpringBoot中,可以使用MyBatis的MapperScannerConfigurer来执行SQL文件。下面是一个示例配置: 1. 在pom.xml文件中添加MyBatis和MySQL的依赖: ```xml <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> </dependencies> ``` 2. 创建一个SQL脚本文件,例如`init.sql`,并将需要执行SQL语句写入该文件。 3. 在`application.properties`或`application.yml`配置文件中添加以下配置: ```properties # MyBatis mybatis.mapper-locations=classpath:mapper/*.xml # SQL脚本 spring.datasource.schema=classpath:init.sql spring.datasource.initialization-mode=always ``` 或者 ```yaml # MyBatis mybatis: mapper-locations: classpath:mapper/*.xml # SQL脚本 spring: datasource: schema: classpath:init.sql initialization-mode: always ``` 4. 创建一个实现了`ApplicationRunner`接口的类,例如`SqlRunner`,并在`run`方法中执行SQL脚本: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.stream.Collectors; @Component public class SqlRunner implements ApplicationRunner { @Autowired private JdbcTemplate jdbcTemplate; @Override public void run(ApplicationArguments args) throws Exception { executeSqlScript("init.sql"); } private void executeSqlScript(String scriptPath) throws IOException { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("classpath:" + scriptPath); for (Resource resource : resources) { String sql = new BufferedReader(new InputStreamReader(resource.getInputStream())) .lines().collect(Collectors.joining("\n")); jdbcTemplate.execute(sql); } } } ``` 这样,在SpringBoot启动时,会自动执行`init.sql`中的SQL语句。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值