java相关:Spring Boot中使用jdbctemplate 操作MYSQL数据库实例
发布于 2020-6-3|
复制链接
本篇文章主要介绍了Spring Boot中使用jdbctemplate 操作MYSQL数据库实例,具有一定的参考价值,有兴趣的可以了解一下。
最近在学习使用Spring Boot连接数据库,今天学习了使用jdbctemplate 操作MYSQL数据库,下面就留个笔记不废话,先来代码pom文件:
```xml
4.0.0
test
test
0.0.1-SNAPSHOT
jar
test
http://maven.apache.org
UTF-8
org.springframework.boot
spring-boot-starter
1.4.2.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
1.4.2.RELEASE
mysql
mysql-connector-java
5.1.21
```
配置文件:application.properties(springboot框架默认使用这个名字,放在resources下面)
```plain
spring.datasource.url=jdbc:mysql://localhost:3306/service_lucky_draw?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.application.name = @pom.artifactId@
server.port=33333
```
启动类:
```java
package versionUpdate;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class ApplicationMain implements CommandLineRunner {
private Logger log = Logger.getLogger(ApplicationMain.class);
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(ApplicationMain.class);
springApplication.run(args);
}
@Override
public void run(String... args) throws Exception {
String queryMerchandiseInfoSql = "SELECT id,worth,channel_id,template_id FROM merchandise_info";
List> list = jdbcTemplate.queryForList(queryMerchandiseInfoSql);
log.debug(list);
}
}
```
至此一个简单的SpringBoot+Jdbctemplate+MYSQL的DEMO搭建完成;如果不想在启动类里面直接进行数据库操作,可以按照下面的方式:
```java
package versionUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/** 获取jdbctemplate实例 */
@Component
public class EnterJdbcTemplate {
private static JdbcTemplate jdbcTemplate;
@Autowired
public EnterJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public static JdbcTemplate getJdbcTemplate(){
return jdbcTemplate;
}
}
```
```java
package versionUpdate;
import org.springframework.jdbc.core.JdbcTemplate;
/** 操作数据库 */
public class Movedata extends EnterJdbcTemplate{
public Movedata(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
public static void ccc(){
System.out.println("++++++++++++++++++"+getJdbcTemplate().queryForMap("SELECT * FROM channel_info WHERE channel_id = ? ","cccc"));
}
}
```