在Springboot中如何直接执行SQL语句
    		       		warning:
    		            这篇文章距离上次修改已过427天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,你可以使用JdbcTemplate来直接执行SQL语句。以下是一个简单的例子:
- 首先,在Spring Boot的配置类中,你需要配置DataSource。
@Configuration
public class DatabaseConfig {
 
    @Bean
    public DataSource dataSource() {
        // 配置数据源,例如使用HikariCP
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/your_database");
        dataSource.setUsername("your_username");
        dataSource.setPassword("your_password");
        return dataSource;
    }
 
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}- 然后,你可以在你的服务类中注入JdbcTemplate并使用它来执行SQL语句。
@Service
public class YourService {
 
    private final JdbcTemplate jdbcTemplate;
 
    @Autowired
    public YourService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    public void executeSql() {
        String sql = "INSERT INTO your_table (column1, column2) VALUES (?, ?)";
        jdbcTemplate.update(sql, "value1", "value2");
    }
}对于查询操作,你可以使用jdbcTemplate.query()方法。
public List<Map<String, Object>> querySql() {
    String sql = "SELECT * FROM your_table";
    return jdbcTemplate.queryForList(sql);
}确保你的Spring Boot项目已经包含了对应的数据库驱动依赖,例如对于MySQL,你需要在pom.xml中添加:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>Your-Version</version>
</dependency>
评论已关闭