文章目录
前言
获取API数据+用Mybatis管理
提示:以下是本篇文章正文内容,下面案例可供参考
一、用Mybatis管理数据库
1.创建数据库data
创建数据库data,建立三张表
2.使用Mybatis连接和管理数据库
(1)创建MAVEN工程,添加Mybatis坐标
在pom.xml文件里添加mybatis,Junit,mysql,log4j坐标
<?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>org.example</groupId>
<artifactId>mybatis02</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
(2)编写实体类
在java下创建project包,在project包中创建domain包
在domain包中,创建三个实体类
CountryDetails.java,CountryList.java,ProvinceDetails.java
CountryDetails.java
package project.domain;
public class CountryDetails {
private Integer iso_country;
private String continent;
private String capital_city;
private Double life_expectancy;
private String abbreviation ;
private Integer confirmed;
private Integer population;
private Integer sq_km_area;
private Integer recovered;
private String elevation_in_meters;
private String location;
private Integer deaths;
public Integer getIso_country() {
return iso_country;
}
public void setIso_country(Integer iso_country) {
this.iso_country = iso_country;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getCapital_city() {
return capital_city;
}
public void setCapital_city(String capital_city) {
this.capital_city = capital_city;
}
public Double getLife_expectancy() {
return life_expectancy;
}
public void setLife_expectancy(Double life_expectancy) {
this.life_expectancy = life_expectancy;
}
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
public Integer getConfirmed() {
return confirmed;
}
public void setConfirmed(Integer confirmed) {
this.confirmed = confirmed;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public Integer getSq_km_area() {
return sq_km_area;
}
public void setSq_km_area(Integer sq_km_area) {
this.sq_km_area = sq_km_area;
}
public Integer getRecovered() {
return recovered;
}
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
public String getElevation_in_meters() {
return elevation_in_meters;
}
public void setElevation_in_meters(String elevation_in_meters) {
this.elevation_in_meters = elevation_in_meters;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Integer getDeaths() {
return deaths;
}
public void setDeaths(Integer deaths) {
this.deaths = deaths;
}
@Override
public String toString() {
return "国家信息{" +
"国家所属洲='" + continent + '\'' +
", 首都='" + capital_city + '\'' +
", 预期寿命=" + life_expectancy +
", 国家名称缩写='" + abbreviation + '\'' +
", 全国确诊数量=" + confirmed +
", 全国总人口=" + population +
", 国家领土大小=" + sq_km_area +
", 全国治愈人数=" + recovered +
", 海拔='" + elevation_in_meters + '\'' +
", 地理位置='" + location + '\'' +
", 全国死亡人数=" + deaths +
'}';
}
}
CountryList.java
package project.domain;
public class CountryList {
private Integer iso;
private String countryName;
public Integer getIso() {
return iso;
}
public void setIso(Integer iso) {
this.iso = iso;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
@Override
public String toString() {
return "国家:'" + countryName + '\'' ;
}
}
ProvinceDetails.java
package project.domain;
public class ProvinceDetails {
private Integer iso_pro;
private String provinceName;
private Integer recovered;
private Integer confirmed;
private String updated;
private Double latitude;
private Double longitude ;
private Integer deaths;
public Integer getIso_pro() {
return iso_pro;
}
public void setIso_pro(Integer iso_pro) {
this.iso_pro = iso_pro;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public Integer getRecovered() {
return recovered;
}
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
public Integer getConfirmed() {
return confirmed;
}
public void setConfirmed(Integer confirmed) {
this.confirmed = confirmed;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Integer getDeaths() {
return deaths;
}
public void setDeaths(Integer deaths) {
this.deaths = deaths;
}
@Override
public String toString() {
return "{" +
"地区名='" + provinceName + '\'' +
", 地区治愈人数=" + recovered +
", 地区确诊人数=" + confirmed +
", 数据更新日期='" + updated + '\'' +
", 纬度=" + latitude +
", 经度=" + longitude +
", 死亡人数=" + deaths +
'}';
}
}
(3)编写持久层接口
在java下的project包中,创建dao包
在dao包中,创建持久层接口,对于domain包中三个实体类。
创建持久层接口ICountryDetailsDao.java,ICountryListDao.java,IProvinceDetailsDao.java
ICountryDetailsDao.java
package project.dao;
import project.domain.CountryDetails;
import java.util.List;
public interface ICountryDetailsDao {
/**
* 根据名字查询国家信息
* @param countryName
* @return
*/
List<CountryDetails>findAll(String countryName);
/**
* 插入国家数据到数据库
* @param countryDetails
*/
void saveCountryDetails(CountryDetails countryDetails);
/**
* 删除国家信息表所有数据
*/
void deleteCountryDetails();
}
ICountryListDao.java
package project.dao;
import project.domain.CountryList;
import java.util.List;
public interface ICountryListDao {
/**
* 查询有哪些国家在数据库中
* @return
*/
List<CountryList> findAll();
/**
* 加入新国家到数据库
* @param countryList
*/
void saveCountryList(CountryList countryList);
/**
* 删除国家列表的所有数据
*/
void deleteCountryList();
}
IProvinceDetailsDao.java
package project.dao;
import project.domain.ProvinceDetails;
import java.util.List;
public interface IProvinceDetailsDao {
/**
* 查询所有地区的信息
* @param countryName
* @return
*/
List<ProvinceDetails>findAll(String countryName);
/**
* 将国家的地区信息插入
* @param provinceDetails
*/
void saveProvinceDetails(ProvinceDetails provinceDetails);
/**
* 删除所有地区信息
*/
void deleteProvinceDetails();
}
(4)编写持久层接口的映射文件
在resources下编写
注意,创建文件的位置必须和持久层接口在相同的包名中,扩展名.xml
导入声明
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
在resources/project/dao下创建
ICountryDetailsDao.xml,ICountryListDao.xml,IProvinceDetailsDao.xml
ICountryDetailsDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="project.dao.ICountryDetailsDao">
<select id="findAll" parameterType="String" resultType="project.domain.CountryDetails">
SELECT countrydetails.*
FROM countrydetails
JOIN countrylist
ON countrydetails.iso_country=countrylist.iso
WHERE countryName=#{countryName}
</select>
<insert id="saveCountryDetails" parameterType="project.domain.CountryDetails">
insert into countrydetails
( iso_country,continent,capital_city,life_expectancy,abbreviation,confirmed, population,sq_km_area,recovered,elevation_in_meters,location,deaths)
values
( #{iso_country},#{continent},#{capital_city},#{life_expectancy},
#{abbreviation},#{confirmed}, #{population},#{sq_km_area},#{recovered},
#{elevation_in_meters},#{location},#{deaths} )
</insert>
<delete id="deleteCountryDetails">
delete from countrydetails
</delete>
</mapper>
ICountryListDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="project.dao.ICountryListDao">
<select id="findAll" resultType="project.domain.CountryList">
select * from countrylist
</select>
<insert id="saveCountryList" parameterType="project.domain.CountryList">
insert into countrylist (iso,countryName) values (#{iso},#{countryName})
</insert>
<delete id="deleteCountryList">
delete from countrylist
</delete>
</mapper>
IProvinceDetailsDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="project.dao.IProvinceDetailsDao">
<select id="findAll" parameterType="String" resultType="project.domain.ProvinceDetails">
SELECT ProvinceDetails.*
FROM ProvinceDetails
JOIN countrylist
ON ProvinceDetails.iso_pro=countrylist.iso
WHERE countryName=#{countryName}
</select>
<insert id="saveProvinceDetails" parameterType="project.domain.ProvinceDetails">
insert into ProvinceDetails (iso_pro,provinceName,recovered,confirmed,updated,latitude,longitude,deaths)
values(#{iso_pro},#{provinceName},#{recovered},#{confirmed},#{updated},#{latitude},#{longitude},#{deaths})
</insert>
<delete id="deleteProvinceDetails">
delete from ProvinceDetails
</delete>
</mapper>
(5)编写SqlMapConfig.xml文件
在resources下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置 mybatis 的环境 -->
<environments default="mysql"> <!-- 配置 mysql 的环境 -->
<environment id="mysql"> <!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置连接数据库的信息:用的是数据源(连接池) -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/west2"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 告知 mybatis 映射配置的位置 -->
<mappers>
<package name="project.dao"></package>
</mappers>
</configuration>
(6)在resources下加入log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
(7)测试
在test下的java里,创建project.test,测试类放在其中
仅展示TestCountryDetails.java中测试代码,其他类似
测试是否能够查询到数据库中数据(已经事前在数据库中存好数据)
package project.test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import project.dao.ICountryDetailsDao;
import project.dao.IProvinceDetailsDao;
import project.domain.CountryDetails;
import project.domain.ProvinceDetails;
import java.io.InputStream;
import java.util.List;
public class TestCountryDetails {
InputStream in ;
SqlSessionFactoryBuilder builder ;
SqlSessionFactory factory;
SqlSession session ;
ICountryDetailsDao countryDetailsDao;
//初始化,配置
@Before//用于测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建 SqlSessionFactory 的构建者对象
builder = new SqlSessionFactoryBuilder();
//3.使用构建者创建工厂对象 SqlSessionFactory
factory = builder.build(in);
//4.使用 SqlSessionFactory 生产 SqlSession 对象
session = factory.openSession();
//5.使用 SqlSession 创建 dao 接口的代理对象
countryDetailsDao = session.getMapper(ICountryDetailsDao.class);
}
//最后,关闭资源
@After//用于测试方法执行之后执行
public void destory()throws Exception{
//6.释放资源
in.close();
}
@Test
public void findAll() {
//5.使用代理对象执行方法
List<CountryDetails> lists = countryDetailsDao.findAll("China");
for(CountryDetails countryDetails : lists){
System.out.println(countryDetails);
}
}
}
控制台
二、获取API的数据存入数据库
1.获取API的数据
API地址:https://covid-api.mmediagroup.fr/v1/cases
获取数据的代码
/**
* 访问该网址的接口获取数据
* @param urlPath
* @return 疫情数据
* @throws Exception
*/
public static String getData(String urlPath) throws Exception {
try {
// 1. 得到访问地址的URL
URL url = new URL(urlPath);
// 2. 得到网络访问对象java.net.HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
/* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
// 设置是否向HttpURLConnection输出
connection.setDoOutput(false);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置请求方式
connection.setRequestMethod("GET");
// 设置是否使用缓存
connection.setUseCaches(true);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(true);
// 设置超时时间
connection.setConnectTimeout(3000);
// 连接
connection.connect();
// 4. 得到响应状态码的返回值 responseCode
int code = connection.getResponseCode();
// 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据
String msg = "";
if (code == 200) { // 正常响应
// 从流中读取响应信息
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) { // 循环从流中读取
msg += line + "\n";
}
reader.close(); // 关闭流
}
// 6. 断开连接,释放资源
connection.disconnect();
return msg;
// 显示响应结果`
// System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
获取API数据的代码是从网上博客学习的,具体出处忘记了,如知可以指出,稍后注明
测试,信息打印在控制台上
2.将数据存入数据库
/**
* 插入数据到数据库中
* @param countryName
* @throws Exception
*/
public void operateOnSQL(String countryName) throws Exception {
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=" + countryName;
try {
/**
* 用变量data存储getData()中读取的数据
* 为了防止网络原因,以下选择将已经读取的数据存入data.json中并利用其中的数据进行测试
*/
String data=getData(url);
JSONObject jsonObject = JSON.parseObject(data);
//存储国家的整体信息
String[] countryMessage = new String[15];
//存储地区的信息
String[] provinceMessage = new String[8];
//连接数据库
Connections connections=new Connections();
//判断是否是国家信息
boolean isAll = false;
int iso = 0;
for (Map.Entry<String, Object> stringObjectEntry : jsonObject.entrySet()) {
String key = stringObjectEntry.getKey();
JSONObject value = (JSONObject) stringObjectEntry.getValue();
if (key == "All") {
isAll = true;//是国家整体信息
}
JSONObject insideJson = value;
int index = 0;
for (Map.Entry<String, Object> insideEntry : insideJson.entrySet()) {
Object getValue = insideEntry.getValue();
//存入数据
if (isAll) {
countryMessage[index++] = getValue.toString();
} else {
provinceMessage[index++] = getValue.toString();
}
}
if (isAll) {//是国家整体数据时
//建立对象CountryList
CountryList countryList = new CountryList();
iso = Integer.parseInt(countryMessage[2]);
countryList.setCountryName(countryMessage[1]);
countryList.setIso(iso);
//并存入数据库
connections.saveCountryListMethod(countryList);
isAll = false;
//建立对象CountryDetails
CountryDetails countryDetails=new CountryDetails();
countryDetails.setIso_country(iso);
countryDetails.setContinent(countryMessage[0]);
countryDetails.setCapital_city(countryMessage[3]);
countryDetails.setLife_expectancy(Double.parseDouble(countryMessage[4]));
countryDetails.setAbbreviation(countryMessage[5]);
countryDetails.setConfirmed(Integer.parseInt(countryMessage[6]));
countryDetails.setPopulation(Integer.parseInt(countryMessage[7]));
countryDetails.setSq_km_area(Integer.parseInt(countryMessage[8]));
countryDetails.setRecovered(Integer.parseInt(countryMessage[9]));
countryDetails.setElevation_in_meters(countryMessage[10]);
countryDetails.setLocation(countryMessage[11]);
countryDetails.setDeaths(Integer.parseInt(countryMessage[12]));
//存入数据库
connections.saveCountryDetailsMethod(countryDetails);
} else {
//存储地区信息
ProvinceDetails provinceDetails=new ProvinceDetails();
provinceDetails.setIso_pro(iso);
provinceDetails.setProvinceName(key);
provinceDetails.setRecovered(Integer.parseInt(provinceMessage[0]));
provinceDetails.setConfirmed(Integer.parseInt(provinceMessage[1]));
provinceDetails.setUpdated(provinceMessage[2]);
provinceDetails.setLatitude("".equals(provinceMessage[3]) ? null : Double.parseDouble(provinceMessage[3]));
provinceDetails.setLongitude("".equals(provinceMessage[4]) ? null : Double.parseDouble(provinceMessage[4]));
provinceDetails.setDeaths(Integer.parseInt(provinceMessage[5]));
//存入数据库
connections.saveProvinceDetailsMethod(provinceDetails);
}
}
System.out.println(countryName+"的数据导入成功。");
} catch (Exception e) {
System.out.println(e.getMessage());
throw new RuntimeException(countryName+"的数据导入失败。");
}
}
将这两个方法一起放入project下的service中的GetData.java
3.连接数据库
在service包中创建Connections.java
注意:@After与@Before只是在测试时有作用,在应用时要手动加入init()方法
package project.service;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import project.dao.ICountryDetailsDao;
import project.dao.ICountryListDao;
import project.dao.IProvinceDetailsDao;
import project.domain.CountryDetails;
import project.domain.CountryList;
import project.domain.ProvinceDetails;
import java.io.InputStream;
import java.util.List;
/**
* 连接数据库
*/
public class Connections {
InputStream in ;
SqlSessionFactoryBuilder builder ;
SqlSessionFactory factory;
SqlSession session ;
static ICountryListDao countryListDao;
static ICountryDetailsDao countryDetailsDao;
static IProvinceDetailsDao provinceDetailsDao;
@Before
public void init() throws Exception{
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建 SqlSessionFactory 的构建者对象
builder = new SqlSessionFactoryBuilder();
//3.使用构建者创建工厂对象 SqlSessionFactory
factory = builder.build(in);
//4.使用 SqlSessionFactory 生产 SqlSession 对象
session = factory.openSession();
//5.使用 SqlSession 创建 dao 接口的代理对象
countryListDao = session.getMapper(ICountryListDao.class);
countryDetailsDao=session.getMapper(ICountryDetailsDao.class);
provinceDetailsDao=session.getMapper(IProvinceDetailsDao.class);
}
//最后,关闭资源
@After
public void destory()throws Exception{
//6.释放资源
in.close();
}
/**
* 在countryList表中插入数据
* @param countryList
* @throws Exception
*/
public void saveCountryListMethod(CountryList countryList) throws Exception {
init();
countryListDao.saveCountryList(countryList);
}
/插入数据///
/**
* 在countryDetails表中插入数据
* @param countryDetails
* @throws Exception
*/
public void saveCountryDetailsMethod(CountryDetails countryDetails) throws Exception {
init();
countryDetailsDao.saveCountryDetails(countryDetails);
}
/**
* 在provinceDetails表中插入数据
* @param provinceDetails
* @throws Exception
*/
public void saveProvinceDetailsMethod(ProvinceDetails provinceDetails) throws Exception {
init();
provinceDetailsDao.saveProvinceDetails(provinceDetails);
}
//查找数据/
/**
* 在countyList中查找数据
* @throws Exception
*/
public void findCountryList() throws Exception {
init();
List<CountryList>list=countryListDao.findAll();
for(CountryList country:list){
System.out.println(country);
}
}
/**
* 在countryDetails表中国家名查找数据
* @param countryName
* @throws Exception
*/
public void findCountryDetails(String countryName) throws Exception {
init();
List<CountryDetails>list=countryDetailsDao.findAll(countryName);
for(CountryDetails country:list){
System.out.println(country);
}
}
/**
* 在provinceDetails表中根据国家名字查找数据
* @param countryName
* @throws Exception
*/
public void findProvinceDetails(String countryName) throws Exception {
init();
List<ProvinceDetails>list=provinceDetailsDao.findAll(countryName);
for(ProvinceDetails province:list){
System.out.println(province);
}
}
//删除数据//
@Test
public void deleteCountryDetails() throws Exception {
init();
countryDetailsDao.deleteCountryDetails();
}
@Test
public void deleteCountryList() throws Exception {
init();
countryListDao.deleteCountryList();
}
@Test
public void deleteProvinceDetails() throws Exception {
init();
provinceDetailsDao.deleteProvinceDetails();
}
/**
*
* @return 返回国家列表
* @throws Exception
*/
@Test
public List<CountryList> CountryNameList() throws Exception {
List<CountryList>list=countryListDao.findAll();
return list;
}
}
三、用户视角
在project下创建view.View.java
package project.view;
import project.domain.CountryList;
import project.service.Connections;
import project.service.GetData;
import java.util.List;
import java.util.Scanner;
public class View {
public static void main(String[] args) throws Exception {
Connections connections=new Connections();
GetData tool=new GetData();
Scanner sc=new Scanner(System.in);
/**
* 预备工作
* 存入中国,美国,英国,日本四个国家的数据
*/
tool.operateOnSQL("China");
tool.operateOnSQL("US");
tool.operateOnSQL("Japan");
tool.operateOnSQL("United Kingdom");
System.out.println("完成预备工作");
/**
*
*/
boolean loop=true;
while (loop){
System.out.println("------疫情数据查询系统------");
System.out.println("1.查询系统疫情数据");
System.out.println("2.向数据库添加新的国家");
System.out.println("3.更新实时数据");
System.out.println("4.退出系统");
System.out.println("请输入您的操作");
///
int next=sc.nextInt();
switch (next){
/**
* 1.查询系统疫情数据
*/
case 1:
System.out.println("请选择您要查询信息的国家");
System.out.println("国家列表");
connections.findCountryList();
System.out.println("请输入国家的名字");
String name=sc.next();
connections.findCountryDetails(name);
System.out.println("是否查询该国家各个地区的疫情数据[yes/no]");
String choose=sc.next();
if(choose.equals("yes")){
connections.findProvinceDetails(name);
System.out.println("以上为该国家疫情数据");
System.out.println("本次查询结束。");
}else{
System.out.println("本次查询结束。");
}
break;
/**
* 2.向数据库添加新的国家
*/
case 2:
System.out.println("请输入您要加入的国家的名字");
String newCountryName=sc.next();
//测试用例:Colombia
tool.operateOnSQL(newCountryName);
System.out.println("添加成功.");
break;
/**
* 3.更新实时数据
*/
case 3:
System.out.println("正在为您更新实时数据中......");
List<CountryList> sets=connections.CountryNameList();
connections.deleteCountryDetails();
connections.deleteCountryList();
connections.deleteProvinceDetails();
System.out.println("成功删除旧数据");
System.out.println("开始导入新数据");
for(int i=0;i<sets.size();i++){
String getName=sets.get(i).getCountryName();
tool.operateOnSQL(getName);
System.out.println("更新"+getName+"的数据成功");
}
System.out.println("更新成功。");
break;
/**
* 4.退出系统
*/
case 4:
System.out.println("退出系统中......");
loop=false;
break;
default:
System.out.println("非法输入");
break;
}
}
System.out.println("感谢您使用疫情数据查询系统");
}
}
总结
以上就是今天要讲的内容,本文仅仅简单介绍了获取API并用Mybatis存入数据库的方法。 缺点:以上代码仅仅针对API中有地区的国家以上是Mybatsi和数据库的学习记录,如有不足,请指出,十分感谢。