博客主页: 南来_北往
🔥系列专栏:Spring Boot实战
要在Spring Boot中使用JdbcTemplate访问MySQL数据库,你需要按照以下步骤操作:
1、添加依赖
在你的pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、配置数据源
在application.properties
文件中配置数据源信息:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3、建JdbcTemplate Bean
在你的配置类中创建一个JdbcTemplate
的Bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class JdbcConfig {
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
4、用JdbcTemplate进行数据库操作
在你的服务类中注入JdbcTemplate
并使用它进行数据库操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void createUser(String name, int age) {
String sql = "INSERT INTO user (name, age) VALUES (?, ?)";
jdbcTemplate.update(sql, name, age);
}
public List<Map<String, Object>> getAllUsers() {
String sql = "SELECT * FROM user";
return jdbcTemplate.queryForList(sql);
}
}
这样你就可以在Spring Boot项目中使用JdbcTemplate访问MySQL数据库了。