php转java 系列2 Spring boo 链接数据库jdbc
JDBC
首先创建一个新项目,在创建项目时要注意导入依赖,
在项目创建成功后就会看到在 pom.xml 文件中找到,但是如果在创建项目的时候没有导入,就要在pom.xml中手动的添加依赖;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
连接数据库
在连接数据库之后,编写数据库配置文件
#访问根路径 #应用名称 spring.application.name=springboot-demo #访问端口号 server.port=8080 #编码格式 server.tomcat.uri-encoding=utf-8 #数据库相关配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://111:3306/wangzhan spring.datasource.username=111 spring.datasource.password=111 spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 #session生命周期 server.servlet.session.timeout=30m
package com.example.demo; import java.util.*; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; @Controller @SpringBootApplication public class DemoApplication { @Autowired private final JdbcTemplate jdbcTemplate; public DemoApplication(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @ResponseBody @RequestMapping("hello1") public String hello1() { Object dddd="fwef"; Object[] ff=new Object[]{"111","1"}; System.out.print("输入你的姓名:"); System.out.print("输入你的姓名1:"); System.out.print("输入你的姓名2:"); // String sql = "insert into t_user(username, password) values(?, ?)"; // // jdbcTemplate.update(sql, new Object[]{"111","1"}); String sql = "SELECT * FROM t_user"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); for (Map<String, Object> map : list) { System.out.println(map); } return "1"; } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/18961.html