https://www.w3cschool.cn/mybatis/mybatis-dyr53b5w.html
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>yubing</groupId>
<artifactId>jdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
</dependencies>
</project>
db.properties
db.user=test
db.password=
db.url=jdbc:mysql://localhost:3306/test?useSSL=no
db.driverClass=com.mysql.jdbc.Driver
公用类Db.java
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Db {
public static JdbcTemplate getJdbcTemplate() {
// 创建Properties类对象
Properties properties = new Properties();
try {
// 读取properties属性文件到输入流中
InputStream is = Db.class.getResourceAsStream("/db.properties");
// 从输入流中加载属性列表
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
// 获取spring的JdbcTemplate
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(properties.getProperty("db.driverClass"));
dataSource.setUrl(properties.getProperty("db.url"));
dataSource.setUsername(properties.getProperty("db.user"));
dataSource.setPassword(properties.getProperty("db.password"));
return new JdbcTemplate(dataSource);
}
}
Demo测试类
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
public class Demo04 {
public static void main(String[] args) {
String sql = null;
JdbcTemplate jdbcTemplate = Db.getJdbcTemplate();
// 查询
sql = "select * from test";
List<Map<String, Object>> users = jdbcTemplate.queryForList(sql);
for (Map<String, Object> user : users) {
System.out.println(user);
}
// 查询为字符串
sql = "select name from test";
List<String> list = jdbcTemplate.queryForList(sql, String.class);
for (String str : list) {
System.out.println(str);
}
// 增加记录
sql = "insert into test set name=?";
jdbcTemplate.update(sql, "dfa");
//修改记录
sql = "update test set name=? where id=?";
jdbcTemplate.update(sql, "fdsdf", 3);
}
}
示例代码可以参考
链接:https://pan.baidu.com/s/198bZHeQS2o17p5oa8exSNA
提取码:java