写一个spring boot的java连接工具
时间: 2024-03-02 12:49:42 浏览: 33
以下是一个简单的使用Spring Boot连接MySQL数据库的示例:
1. 首先在pom.xml中添加MySQL数据库驱动依赖:
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
```
2. 在application.properties中添加数据库连接配置:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建一个数据库连接工具类:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class DBUtil {
@Autowired
private JdbcTemplate jdbcTemplate;
public void query() {
String sql = "SELECT * FROM test_table";
jdbcTemplate.query(sql, (rs, rowNum) ->
new Test(rs.getInt("id"), rs.getString("name"))
).forEach(System.out::println);
}
public static class Test {
private int id;
private String name;
public Test(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Test{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
}
```
4. 在Spring Boot应用中使用该工具类:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
@Autowired
private DBUtil dbUtil;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void run(String... args) throws Exception {
dbUtil.query();
}
}
```
这里的DBUtil使用了Spring Boot提供的JdbcTemplate来执行SQL语句,可以方便地进行数据库操作。在Application类中,通过@Autowired注解将DBUtil注入进来,然后在run方法中调用DBUtil的query方法来执行SQL查询。