Spring Boot中使用jdbctemplate 操作MYSQL数据库实例
最近在学习使用SpringBoot连接数据库,今天学习了使用jdbctemplate操作MYSQL数据库,下面就留个笔记
不废话,先来代码
pom文件:
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下面)
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
启动类:
packageversionUpdate; importjava.util.List; importjava.util.Map; importorg.apache.log4j.Logger; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.boot.CommandLineRunner; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.jdbc.core.JdbcTemplate; @SpringBootApplication publicclassApplicationMainimplementsCommandLineRunner{ privateLoggerlog=Logger.getLogger(ApplicationMain.class); @Autowired privateJdbcTemplatejdbcTemplate; publicstaticvoidmain(String[]args){ SpringApplicationspringApplication=newSpringApplication(ApplicationMain.class); springApplication.run(args); } @Override publicvoidrun(String...args)throwsException{ StringqueryMerchandiseInfoSql="SELECTid,worth,channel_id,template_idFROMmerchandise_info"; List
至此一个简单的SpringBoot+Jdbctemplate+MYSQL的DEMO搭建完成;
如果不想在启动类里面直接进行数据库操作,可以按照下面的方式:
packageversionUpdate; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.jdbc.core.JdbcTemplate; importorg.springframework.stereotype.Component; /**获取jdbctemplate实例*/ @Component publicclassEnterJdbcTemplate{ privatestaticJdbcTemplatejdbcTemplate; @Autowired publicEnterJdbcTemplate(JdbcTemplatejdbcTemplate){ this.jdbcTemplate=jdbcTemplate; } publicstaticJdbcTemplategetJdbcTemplate(){ returnjdbcTemplate; } }
packageversionUpdate; importorg.springframework.jdbc.core.JdbcTemplate; /**操作数据库*/ publicclassMovedataextendsEnterJdbcTemplate{ publicMovedata(JdbcTemplatejdbcTemplate){ super(jdbcTemplate); } publicstaticvoidccc(){ System.out.println("++++++++++++++++++"+getJdbcTemplate().queryForMap("SELECT*FROMchannel_infoWHEREchannel_id=?","cccc")); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。