spring jdbc 操作 mysql

build.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'gs-serving-web-content'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework:spring-jdbc")
compile("mysql:mysql-connector-java:5.1.24")
compile("org.springframework.boot:spring-boot-devtools")
testCompile("junit:junit")
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import hello.User;
import java.util.List;
/**
* Created by Administrator on 2016/9/29 0029.
*/
public class Test {
private JdbcTemplate jdbcTemplate;
private static final Logger log = LoggerFactory.getLogger(Test.class);
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public String getName() {
return this.jdbcTemplate.queryForObject("select name from users limit 1", String.class);
}
public List<User> getList() {
return jdbcTemplate.query(
"SELECT id, name, email,created_at FROM users",
(rs, rowNum) -> new User(rs.getString("id"), rs.getString("email"), rs.getString("name"),rs.getBigDecimal("created_at"))
);
}
public static void main(String[] args){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/awesome");
dataSource.setUsername("root");
dataSource.setPassword("root");
Test test=new Test();
test.setDataSource(dataSource);
//String name=test.getName();
List<User> list = test.getList();
list.forEach(user->System.out.println(user));
}
}