如何用maven新建项目,用maven建项目的优势,常用的io工具和durid工具
参考博客 :
【配置】Maven的配置 & Tomcat的配置 & 在IDEA中新建web项目
中的maven配置
package com.tianju.io;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;
import java.util.List;
public class ReadFileDemo1 {
public static void main(String[] args) throws IOException {
// IOUtils 进行读取
/**
* IOUtils.readLines 读取一个文件,把文件中的每一行放在一个List中
* 两个参数: 1.要读取文件的输入流 FileInputStream;
* 2.编码形式,通常为"UTF-8"
*/
List<String> stringList = IOUtils.readLines(new FileInputStream("D:\\Myprogram\\jf_map_utf8.txt"),
"UTF-8");
stringList.forEach(System.out::println);
// 读文件
List<String> in = FileUtils.readLines(new File("D:\\Myprogram\\jf_map_utf8.txt"),"UTF-8");
System.out.println(in);
// 读网页
URL url = new URL("https://www.baidu.com");
InputStream inputStream = url.openStream();
List<String> stringList1 = IOUtils.readLines(inputStream,"UTF-8");
stringList1.forEach(System.out::println);
}
}
package com.tianju.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TransferDemo1 {
public static void main(String[] args) throws IOException {
String filePath = "D:\\Myprogram\\jf_map_utf8.txt";
List<String> in = FileUtils.readLines(new File(filePath),"UTF-8");
// 把list 转成 map,高效查找
Map<String,String> map = new HashMap<>(1000);
for (String i:in){
String[] iSplit = i.split(":");
map.put(iSplit[0],iSplit[1]);
}
// 转换单个字的方法
System.out.println(map);
String inStr = "发";
System.out.println(map.get(inStr));
// 转换一句话的方法
String inWord = "我家住在东北6564呵呵,恭喜发财";
StringBuilder outWord = new StringBuilder();
char[] chars = inWord.toCharArray();
for (char c:chars){
// 如果是中文字符,则进行繁体字的转换
if (Character.UnicodeScript.of(c)==Character.UnicodeScript.HAN){
if (map.get(c+"")!=null){
outWord.append(map.get(c+""));
}else {
outWord.append(c);
}
}else {
// 否则直接加加进去
outWord.append(c);
}
}
System.out.println(outWord);
}
}
(1)用durid去连接数据库,创建多个connection;
(2)要用到connection的时候,找durid要;
连接数据库的两种url写法:
String url = "jdbc:mysql://127.0.0.1:3306/javaweb06?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
String url = "jdbc:mysql://"+ip+"?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
package com.tianju.dataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import java.sql.SQLException;
/**
* 1.用 druid 去连接数据库,创建多个connection
* 2.要用到connection 的时候,找druid要
*/
public class DruidDemo {
public static void main(String[] args) throws SQLException {
String driverClassname = "com.mysql.cj.jdbc.Driver";
String ip = "192.168.111.128:3306/rec_db";
String url = "jdbc:mysql://"+ip+"?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
String username = "root";
String password = "123";
// 1.创建Druid 的连接对象,会一次性创建10个连接
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassname);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(10); // 让数据库一次性建立10个连接
// 2.使用一个连接,问druid要一个连接
DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
}
}
推荐使用queryForObject、query
RowMapper<Emp> userRowMapper = new BeanPropertyRowMapper<>(Emp.class);
List<Emp> empList = jdbcTemplate.query("SELECT * FROM emp_tab", userRowMapper);
根据id查单个的方式:
public Phone findById(Integer id) {
List<Phone> find = db.query("SELECT * FROM t_phone WHERE id = ?", rowMapper,id);
if (find.size()>0){
return find.get(0);
}
System.out.println("Not found");
return null;
}
package com.tianju.dataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.tianju.entity.Emp;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JdbcTmpelateDemo {
public static void main(String[] args) throws SQLException {
String driverClassname = "com.mysql.cj.jdbc.Driver";
String ip = "192.168.111.128:3306/emp_db";
String url = "jdbc:mysql://"+ip+"?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
String username = "root";
String password = "123";
// 1.创建Druid 的连接对象,会一次性创建10个连接
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassname);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(10); // 让数据库一次性建立10个连接
// 2.jdbcTemplate, 操作数据库的工具类,类似于DBUtils
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// 增删改
jdbcTemplate.update("INSERT INTO emp_tab(emp_name, emp_gender) VALUES (?,?)","张三","女");
// 查询,不建议用此方法
SqlRowSet rs = jdbcTemplate.queryForRowSet("SELECT * FROM emp_tab");
List<Emp> list = new ArrayList<>(10);
while (rs.next()){
Emp emp = new Emp(
rs.getInt("id"),
rs.getString("name"),
rs.getString("gender"),
rs.getInt("age"),
rs.getDouble("sal"),
rs.getString("job")
);
list.add(emp);
}
System.out.println(list);
// 查询的第二种方式,这种方式更好
RowMapper<Emp> userRowMapper = new BeanPropertyRowMapper<>(Emp.class);
List<Emp> empList = jdbcTemplate.query("SELECT * FROM emp_tab", userRowMapper);
System.out.println("-----------------");
System.out.println(empList);
}
}
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.tianjugroupId>
<artifactId>JavaWebPhoneartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.16version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.20version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.22.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>RELEASEversion>
<scope>compilescope>
dependency>
dependencies>
project>
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
package com.tianju.test;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.tianju.util.DBUtils;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class SaveToSQLDemo1 {
public static void main(String[] args) throws IOException {
JdbcTemplate db = DBUtils.getJdbcTemplate();
String filePath = "D:\\Myprogram\\files\\phone1.csv";
List<String> stringList = FileUtils.readLines(new File(filePath),"UTF-8");
for (int i =1;i<stringList.size();i++){
String[] sSplit = stringList.get(i).split(",");
System.out.println(sSplit[1] + sSplit[2] + sSplit[3]);
db.update("INSERT INTO t_phone(mobile_number,mobile_area,mobile_type,create_time,update_time) " +
"VALUES (?,?,?,now(),now())",sSplit[1],sSplit[2],sSplit[3]);
}
}
@Test // 加入test注解,让普通方法变成可运行
public void insertInSQL() throws IOException {
JdbcTemplate db = DBUtils.getJdbcTemplate();
String filePath = "D:\\Myprogram\\files\\phone1.csv";
List<String> stringList = FileUtils.readLines(new File(filePath),"UTF-8");
for (int i =1;i<stringList.size();i++){
String[] sSplit = stringList.get(i).split(",");
System.out.println(sSplit[1] + sSplit[2] + sSplit[3]);
db.update("INSERT INTO t_phone(mobile_number,mobile_area,mobile_type,create_time,update_time) " +
"VALUES (?,?,?,now(),now())",sSplit[1],sSplit[2],sSplit[3]);
}
}
}
package com.tianju.util;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 1.连接数据库--durid
* 2.提供jdbcTemplate
*/
public class DBUtils {
private static DruidDataSource dataSource =null;
static {
String driverClassname = "com.mysql.cj.jdbc.Driver";
String ip = "127.0.0.1:3306/javaweb06";
// jdbc:mysql://127.0.0.1:3306/javaweb06?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8
String url = "jdbc:mysql://"+ip+"?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
String username = "root";
String password = "123";
dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassname);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
}
/**
*
* @return 返回一个JdbcTemplate对象
*/
public static JdbcTemplate getJdbcTemplate(){
return new JdbcTemplate(dataSource);
}
}
接口部分
package com.tianju.dao;
import com.tianju.entity.Phone;
import java.util.List;
public interface IPhoneDao {
// 添加一条数据
/**
* 增加一条数据
* @param phone 增加的实体类
* @return 返回影响的行数
*/
Integer add(Phone phone);
// 修改
/**
* 修改
* @param phone 修改的实体类,根据该实体类的id进行定位和修改
* @return 影响行数
*/
Integer update(Phone phone);
// 根据id删除一条数据
/**
* 根据id删除一条数据
* @param id 删除的索引id
* @return 影响行数
*/
Integer deleteById(Integer id);
// 查询所有
/**
* 查询数据库中所有的数据
* @return 查询到的list
*/
List<Phone> queryAll();
// 根据id查询
Phone findById(Integer id);
// 根据mobile_number进行查询
/**
* 根据号码查询归属地等信息
* @param mobileNumber 查找的电话number
* @return 返回查找的
*/
Phone selectByMobileNumber(String mobileNumber);
// 查询数据条数
/**
* 查找所有的行数
* @return 总的行数
*/
Integer countDataLines();
}
实现类
package com.tianju.dao.impl;
import com.tianju.dao.IPhoneDao;
import com.tianju.entity.Phone;
import com.tianju.util.DBUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
public class PhoneDaoImpl implements IPhoneDao {
private JdbcTemplate db;
private RowMapper<Phone> rowMapper;
public PhoneDaoImpl() {
db = DBUtils.getJdbcTemplate();
rowMapper = new BeanPropertyRowMapper<>(Phone.class);
}
@Override
public Integer add(Phone phone) {
return db.update("INSERT INTO t_phone(id,mobile_number,mobile_area,mobile_type,create_time,update_time) VALUES " +
"(NULL,?,?,?,now(),now())",phone.getMobileNumber(),phone.getMobileArea(),phone.getMobileType());
}
@Override
public Integer update(Phone phone) {
return db.update("UPDATE t_phone SET mobile_number=?,mobile_area=?,mobile_type=?,update_time=now() WHERE id=?",
phone.getMobileNumber(),phone.getMobileArea(),phone.getMobileType(),phone.getId());
}
@Override
public Integer deleteById(Integer id) {
return db.update("DELETE FROM t_phone WHERE id = ?", id);
}
@Override
public List<Phone> queryAll() {
return db.query("SELECT * FROM t_phone", rowMapper);
}
@Override
public Phone findById(Integer id) {
List<Phone> find = db.query("SELECT * FROM t_phone WHERE id = ?", rowMapper,id);
if (find.size()>0){
return find.get(0);
}
System.out.println("Not found");
return null;
}
@Override
public Phone selectByMobileNumber(String mobileNumber) {
List<Phone> find = db.query("SELECT * FROM t_phone WHERE mobile_number = ?", rowMapper,mobileNumber);
if (find.size()>0){
return find.get(0);
}
System.out.println("Not found");
return null;
}
@Override
public Integer countDataLines() {
// 要用.queryForObject方法
return db.queryForObject("SELECT COUNT(*) FROM t_phone", Integer.class);
}
}
package com.tianju.entity;
import lombok.*;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Setter @Getter
public class Phone {
private Integer id;
private String mobileNumber;
private String mobileArea;
private String mobileType;
private Date createTime; // springJDBC可以把数据中下划线转成createTime
private Date updateTime;
@Override
public String toString() {
return "\nPhone{" +
"id=" + id +
", mobileNumber='" + mobileNumber + '\'' +
", mobileArea='" + mobileArea + '\'' +
", mobileType='" + mobileType + '\'' +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}
package test;
import com.tianju.dao.IPhoneDao;
import com.tianju.dao.impl.PhoneDaoImpl;
import com.tianju.entity.Phone;
import org.junit.Test;
import java.util.stream.Collectors;
public class PhoneDaoTest {
private IPhoneDao dao = new PhoneDaoImpl();
@Test
public void add(){
// 添加
System.out.println(dao.countDataLines());
System.out.println(dao.add(new Phone(null, "测试", "测试1", "南京", null, null)));
System.out.println(dao.countDataLines());
}
@Test
public void update(){
// 修改
System.out.println(dao.findById(300107));
System.out.println(dao.update(new Phone(300107, "南京", "江宁", "hehe", null, null)));
System.out.println(dao.findById(300107));
}
@Test
public void query(){
// 查询
System.out.println(dao.countDataLines());
System.out.println(dao.queryAll().stream().limit(10).collect(Collectors.toList()));
System.out.println(dao.selectByMobileNumber("1880222"));
}
@Test
public void delete(){
System.out.println(dao.deleteById(300106));
}
}
1.maven的作用,及其配置,新建maven项目方法;
2.常用的IO工具,读取文件的方法,读取到成字符串行;
3.durid数据库连接工具,查询的方法,query;