第三章 DAO模式《分层》 ② 代码
1.用户登录管理系统(拓展:图书管理)0723
创建表 users、book
#创建用户表
create table users
(
userId int primary key auto_increment,
userName varchar(20),
password varchar(20),
nikeName varchar(20),
sex varchar(5),
phone varchar(20)
);
select * from users;
create table book
(
bookId int primary key auto_increment,
bookName varchar(200),
author varchar(20),
price decimal(5,1),
pubDate date
);
select * from book;
添加jar包: 数据库jar包,并引用
项目代码:
util
BaseDAO.java
package com.yzh7.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseDAO {
//四大金刚
//驱动类
private static final String DRIVER="com.mysql.cj.jdbc.Driver";
//连接地址
private static final String URL="jdbc:mysql://localhost:3306/0723_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
//用户名
private static final String USER="root";
//密码
private static final String PASSWORD="123456";
//获取连接
public static Connection getConnection(){
Connection con = null;
try{
//加载驱动类
Class.forName(DRIVER);
//获取连接
con = DriverManager.getConnection(URL,USER,PASSWORD);
}catch(Exception ex){
ex.printStackTrace();
}
return con;
}
//关闭数据库对象
public static void closeAll(Connection con,Statement st,ResultSet rs){
if(rs!=null){
try{
rs.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(st!=null){
try{
st.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(con!=null){
try{
con.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用设置参数方法
public static void setParams(PreparedStatement pst,Object[] params){
if(params==null){
return;
}
for(int i=0;i<params.length;i++){
try{
pst.setObject(i+1,params[i]);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用增删改
public static int executeUpdate(String sql,Object[] params){
Connection con = null;
PreparedStatement pst = null;
int res = -1;
try{
//获取连接
con = getConnection();
//创建预编译命令执行对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行
res = pst.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,null);
}
return res;
}
//通用查询
public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {
List<Map<String,Object>> rows = new ArrayList<>();
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
//获取连接
con = getConnection();
//获取命令对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行查询
rs = pst.executeQuery();
//通过rs获取结果集的结构信息
ResultSetMetaData rsmd = rs.getMetaData();
//获取结果集的列数
int colCount = rsmd.getColumnCount();
//遍历查询结果,并封装到List<Map>中
while(rs.next()){
//用Map存储当前行的各个列数据
Map<String,Object> map = new HashMap<>();
//循环获取每一列的信息
for(int i=1;i<=colCount;i++){
//获取列名(使用rsmd)
String colName = rsmd.getColumnLabel(i);
//获取列值(使用rs)
Object colVal = rs.getObject(i);
//将当前列存储到map中
map.put(colName,colVal);
}
//将遍历的当前行的数据存储到List中
rows.add(map);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,rs);
}
return rows;
}
}
entity
Users.java
package com.yzh7.entity;
/**
* @author: hy
* @create: 2022-07-23 10:54:27
*/
public class Users {
//编号
private Integer userId;
//用户名
private String userName;
//密码
private String password;
//昵称
private String nickName;
//性别
private String sex;
//手机
private String phone;
public Users() {
}
public Users(Integer userId, String userName, String password, String nickName, String sex, String phone) {
this.userId = userId;
this.userName = userName;
this.password = password;
this.nickName = nickName;
this.sex = sex;
this.phone = phone;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", nickName='" + nickName + '\'' +
", sex='" + sex + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
Book.java
package com.yzh7.entity;
/**
* @author: hy
* @create: 2022-07-23 11:57:07
*/
public class Book {
}
dao
IUsersDAO.java
package com.yzh7.dao;
import com.yzh7.entity.Users;
import java.util.List;
import java.util.Map;
/**
* 数据访问层用户接口
*/
public interface IUsersDAO {
//根据用户名和密码查询用户账号
Users getByUserNameAndPassword(String userName, String password);
//根据用户名查询数据,判断用户名是否存在
boolean getByUserName(String userName);
//根据手机查询数据,判断手机是否存在
boolean getByPhone(String phone);
//添加用户
int insert(Users users);
}
IBookDAO.java
package com.yzh7.dao;
import com.yzh7.entity.Book;
import java.util.List;
import java.util.Map;
/**
* @author: hy
* @create: 2022-07-23 11:57:35
*/
public interface IBookDAO {
//查询所有
List<Map<String,Object>> list();
int insert(Book book);
int update(Book book);
int delete(Integer bookId);
}
impl
UsersDAOImpl.java
package com.yzh7.dao.impl;
import com.yzh7.dao.IUsersDAO;
import com.yzh7.entity.Users;
import com.yzh7.util.BaseDAO;
import java.util.List;
import java.util.Map;
/**
* 数据访问层实现类
* @author: hy
* @create: 2022-07-23 11:03:52
*/
public class UsersDAOImpl implements IUsersDAO {
/**
* 根据用户名和密码查询账号
* @param userName
* @param password
* @return
*/
@Override
public Users getByUserNameAndPassword(String userName, String password) {
String sql = "select userId,userName,password,nickName,sex,phone " +
" from users " +
" where userName = ? and password = ? ";
Object[] params = {userName,password};
//条件查询
List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
//如果有数据,则封装查询结果,返回users对象
if(rows.size()>0){
//获取集合中的第一条
Map<String,Object> map = rows.get(0);
//将Map中的数据,转为Users对象
Users users = new Users();
users.setUserId((Integer) map.get("userId"));
users.setUserName((String) map.get("userName"));
users.setPassword((String) map.get("password"));
users.setNickName((String) map.get("nickName"));
users.setSex((String) map.get("sex"));
users.setPhone((String) map.get("phone"));
return users;
}
//账号密码不正确,则返回空
return null;
}
/**
* 校验账号是否存在
* @param userName
* @return
*/
@Override
public boolean getByUserName(String userName) {
String sql = "select userId,userName,password,nickName,sex,phone " +
" from users " +
" where userName = ? ";
Object[] params = {userName};
List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
//返回对应的账号是否存在
return rows.size()>0;
}
/**
* 校验手机是否存在
* @param phone
* @return
*/
@Override
public boolean getByPhone(String phone) {
String sql = "select userId,userName,password,nickName,sex,phone " +
" from users " +
" where phone = ? ";
Object[] params = {phone};
List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
return rows.size()>0;
}
/**
* 插入数据
* @param users
* @return
*/
@Override
public int insert(Users users) {
String sql = "insert into users " +
" (userName,password,nickName,sex,phone)" +
" values" +
" (?,?,?,?,?)";
Object[] params = {
users.getUserName(),
users.getPassword(),
users.getNickName(),
users.getSex(),
users.getPhone()
};
return BaseDAO.executeUpdate(sql,params);
}
}
BookDAOImpl.java
package com.yzh7.dao.impl;
import com.yzh7.dao.IBookDAO;
import com.yzh7.entity.Book;
import java.util.List;
import java.util.Map;
/**
* @author: hy
* @create: 2022-07-23 11:58:35
*/
public class BookDAOImpl implements IBookDAO {
@Override
public List<Map<String, Object>> list() {
return null;
}
@Override
public int insert(Book book) {
return 0;
}
@Override
public int update(Book book) {
return 0;
}
@Override
public int delete(Integer bookId) {
return 0;
}
}
service
IUsersService.java
package com.yzh7.service;
/**
* 定义用户业务层接口
*/
public interface IUsersService {
//登陆业务
boolean login();
//注册业务
boolean regist();
}
IBookService.java
package com.yzh7.service;
import com.yzh7.entity.Book;
import java.util.List;
import java.util.Map;
/**
* @author: hy
* @create: 2022-07-23 11:58:57
*/
public interface IBookService {
List<Map<String,Object>> list();
int add(Book book);
int update(Book book);
int delete(Integer bookId);
}
impl
UsersServiceImpl.java
package com.yzh7.service.impl;
import com.mysql.cj.util.StringUtils;
import com.yzh7.dao.IUsersDAO;
import com.yzh7.dao.impl.UsersDAOImpl;
import com.yzh7.entity.Users;
import com.yzh7.service.IUsersService;
import java.util.Scanner;
/**
* 用户业务的实现类
* @author: hy
* @create: 2022-07-23 11:22:36
*/
public class UsersServiceImpl implements IUsersService {
@Override
public boolean login() {
//1.输入账号和密码
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName = scanner.next();
System.out.println("请输入密码:");
String password = scanner.next();
//2.校验账号密码是否为空
if(StringUtils.isNullOrEmpty(userName.trim())){
System.out.println("用户名不能为空");
return false;
}
if(StringUtils.isNullOrEmpty(password.trim())){
System.out.println("密码不能为空");
return false;
}
//3.查询对应的账号密码是否存在
//创建数据访问层对象,调用对用的方法,完成业务需要
IUsersDAO usersDAO = new UsersDAOImpl();
Users users = usersDAO.getByUserNameAndPassword(userName,password);
if(users==null){
System.out.println("账号和密码不正确....");
return false;
}
System.out.println("登陆成功....");
return true;
}
@Override
public boolean regist() {
//1.输入注册信息
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName= scanner.next();
System.out.println("请输入密码:");
String password = scanner.next();
System.out.println("请输入昵称:");
String nickName = scanner.next();
System.out.println("请输入性别:");
String sex = scanner.next();
System.out.println("请输入手机:");
String phone = scanner.next();
//2.校验数据是否为空
if(StringUtils.isNullOrEmpty(userName.trim())){
System.out.println("用户名不能为空");
return false;
}
if(StringUtils.isNullOrEmpty(password.trim())){
System.out.println("密码不能为空");
return false;
}
//....
//3.唯一性校验:判断用户名是否唯一,判断手机是否唯一
IUsersDAO usersDAO =new UsersDAOImpl();
if(usersDAO.getByUserName(userName)){
System.out.println("该用户名已经存在,不能使用...");
return false;
}
if(usersDAO.getByPhone(phone)){
System.out.println("该手机已经备使用,不能再次使用....");
return false;
}
//4.插入数据,完成注册
Users users = new Users();
users.setUserName(userName);
users.setPassword(password);
users.setSex(sex);
users.setPhone(phone);
users.setNickName(nickName);
//使用数据访问层插入数据
int count = usersDAO.insert(users);
if(count==1){
System.out.println("注册成功");
return true;
}
System.out.println("注册失败");
return false;
}
}
BookServiceImpl.java
package com.yzh7.service.impl;
import com.yzh7.dao.IBookDAO;
import com.yzh7.dao.impl.BookDAOImpl;
import com.yzh7.entity.Book;
import com.yzh7.service.IBookService;
import java.util.List;
import java.util.Map;
/**
* @author: hy
* @create: 2022-07-23 12:00:16
*/
public class BookServiceImpl implements IBookService {
IBookDAO bookDAO = new BookDAOImpl();
@Override
public List<Map<String, Object>> list() {
return bookDAO.list();
}
@Override
public int add(Book book) {
return bookDAO.insert(book);
}
@Override
public int update(Book book) {
return bookDAO.update(book);
}
@Override
public int delete(Integer bookId) {
return bookDAO.delete(bookId);
}
}
app
App.java
package com.yzh7.app;
import com.yzh7.service.IUsersService;
import com.yzh7.service.impl.UsersServiceImpl;
import java.util.Scanner;
/**
* @author: hy
* @create: 2022-07-23 10:56:21
*/
public class App {
public static void bookMgr(){
System.out.println("1.添加 2.修改 3.删除 4.查询 5.退出");
}
public static void main(String[] args) {
System.out.println("==================");
System.out.println("=欢迎使用图书管理系统=");
System.out.println("==================");
Scanner scanner = new Scanner(System.in);
IUsersService usersService = new UsersServiceImpl();
while (true) {
System.out.println("请选择:1.登陆 2.注册 3.退出");
int choose = scanner.nextInt();
switch (choose){
case 1:
System.out.println("你选择了登陆...");
boolean isLoginSuc = usersService.login();
if(isLoginSuc){
System.out.println("进入图书管理系统...");
bookMgr();
}
break;
case 2:
System.out.println("你选择了注册...");
boolean isRegitSuc = usersService.regist();
break;
case 3:
System.out.println("退出,欢迎下次使用...");
return;
default:
System.out.println("选择错误....");
break;
}
}
}
}
// A code block
var foo = 'bar';
2.拓展图书管理系统设计(结合课前测0725)
0.确定业务功能,图书管理
------------------
1.建库建表: Book
2.创建java项目
3.添加jar包: 数据库jar包,并引用
4.创建util包,创建BaseDAO工具类
5.创建实体包,创建实体类
实体包: entity,
实体类: Book(实体类一般和表名一致)
6.创建数据访问层包/实现包,创建数据访问层接口,创建数据访问层实现类
数据访问层包: dao
数据访问层接口: IBookDAO
数据访问层实现包: impl
数据访问层实现类: BookDAOImpl
7.创建业务层包/实现包,业务层接口,业务层实现类
业务层包: service
业务层层接口: IBookService
业务层实现包: impl
业务层实现类: BookServiceImpl
8.创建程序入口,进行测试
3. 自动代码生成 0725
package com.aaa.code.gen;
/**
* @author: hy
* @create: 2022-07-25 10:56:27
*/
public class CodeGenUtil {
/**
* 根据数据库类型获取java类型
* @param dbType
* @return
*/
public static String getJavaType(String dbType){
if("VARCHAR".equalsIgnoreCase(dbType)||
"CHAR".equalsIgnoreCase(dbType)){
return "String";
}else if("DOUBLE".equalsIgnoreCase(dbType)||
"FLOAT".equalsIgnoreCase(dbType)||
"DECIMAL".equalsIgnoreCase(dbType)){
return "Double";
}else if("INT".equalsIgnoreCase(dbType)){
return "Integer";
}else if("DATE".equalsIgnoreCase(dbType)){
return "Date";
}
return null;
}
}
package com.aaa.code.gen;
import com.aaa.util.BaseDAO;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
/**
* @author: hy
* @create: 2022-07-25 10:48:41
*/
public class Test {
public static void main(String[] args) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String tabName = "Student";
String sql = "select * from "+tabName+" where 1<>1 ";
try{
con = BaseDAO.getConnection();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
//查询的表结构
ResultSetMetaData metaData = rs.getMetaData();
//获取表的列数
int colCount = metaData.getColumnCount();
StringBuilder strJavaEntity =new StringBuilder();
strJavaEntity.append("public class "+tabName+"{\r\n");
//获取每一个列的信息
for (int i=1;i<=colCount;i++){
String colName = metaData.getColumnName(i);
String colType = metaData.getColumnTypeName(i);
//System.out.println("private "+CodeGenUtil.getJavaType(colType)+" "+colName+";");
strJavaEntity.append("\tprivate "+CodeGenUtil.getJavaType(colType)+" "+colName+";\r\n");
}
strJavaEntity.append("}");
System.out.println(strJavaEntity);
//打印java类内容到磁盘文件
PrintWriter out = new PrintWriter("D:/"+tabName+".java");
out.println(strJavaEntity);
out.flush();
out.close();
}catch (Exception ex){
ex.printStackTrace();
}finally {
BaseDAO.closeAll(con,pst,rs);
}
}
}
4. log4j的使用(日志工具)
Project / log4j.properties
### 把日志信息输出到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#使用的输出对象
log4j.appender.stdout.Target=System.out
#设置输出内容格式类型
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#设置格式的具体配置
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %M %F %p %m%n
### 把日志信息输出到文件:anbo.log ###
#设置输出到文件中
log4j.appender.file=org.apache.log4j.FileAppender
#设置输出文件的文件名
log4j.appender.file.File=test.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %m%n
### 把日志信息输出到文件:d:/mylog.txt ###
#设置输出到文件中
log4j.appender.xxx=org.apache.log4j.FileAppender
#设置输出文件的文件名
log4j.appender.xxx.File=d:/mylog.txt
log4j.appender.xxx.layout=org.apache.log4j.PatternLayout
log4j.appender.xxx.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %m%n
### 设置优:先级别、以及输出源(多个) ###
log4j.rootLogger=info,stdout,xxx
Project / 代码目录 /…/ MyTest
package com.aaa.test;
import org.apache.log4j.Logger;
/**
* @author: hy
* @create: 2022-07-25 11:15:11
*/
public class MyTest {
public static void main(String[] args) {
//创建Log4j的日志记录器对象
Logger logger = Logger.getLogger(MyTest.class);
// debug<info<warn<error<fatal
logger.debug("这是debug调试级别的内容");
logger.info("这是info级别的内容");
logger.warn("这是warn警告级别的内容");
logger.error("这是error错误级别的内容");
logger.fatal("这是fatal严重错误的内容");
}
}
package com.aaa.test;
import org.apache.log4j.Logger;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @author: hy
* @create: 2022-07-25 11:33:15
*/
public class MyTest2 {
public static void main(String[] args) {
//在什么场景下使用log4j
Logger log = Logger.getLogger(MyTest2.class);
log.debug("运算程序开始执行");
Scanner scanner =new Scanner(System.in);
try {
log.debug("准备输入第一个数");
System.out.println("请输入第一个数:");
int num1 = scanner.nextInt();
log.info("输入的第一个数:"+num1);
log.debug("准备输入第二个数");
System.out.println("请输入第二个数:");
int num2 = scanner.nextInt();
log.info("输入的第二个数:"+num2);
log.debug("准备运算结果");
int res = num1/num2;
log.info("计算结果是:"+res);
//System.out.println("结果:"+res);
} catch (ArithmeticException exception) {
log.error("发生了数学运算异常:"+exception.getMessage());
exception.printStackTrace();
} catch (InputMismatchException exception){
log.error("发生了输入不匹配异常:"+exception.getMessage());
exception.printStackTrace();
}
log.debug("程序执行结束");
}
}
练习1.用户管理系统设计
创建表 users
#创建用户表
create table users
(
userId int primary key auto_increment,
userName varchar(20),
password varchar(20),
nikeName varchar(20),
sex varchar(5),
phone varchar(20)
);
select * from users;
添加jar包
项目代码:
util
BAO.java
package com.yzh70723.keqiance;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author: XYT
* @create-date: 2022/7/23 9:01
*/
public class BAO {
private static String driver="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/70723_db1?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
private static String user="root";
private static String password="123456";
public static Connection getConnection(){
Connection con=null;
try {
Class.forName(driver);
con= DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return con;
}
public static void closeAll(Connection con, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void setParams(PreparedStatement pst,Object[] params){
if(params==null){
return;
}
//设置参数
for (int i = 0; i < params.length; i++) {
try {
pst.setObject(i+1,params[i]);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static int executeUpdate(String sql, Object[] params){
Connection con=null;
PreparedStatement pst=null;
int res=-1;
try {
con=getConnection();
pst=con.prepareStatement(sql);
setParams(pst,params);
res=pst.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
closeAll(con,pst,null);
}
return res;
}
public static java.util.List<Map<String, Object>> exeucteQuery(String sql, Object[] params){
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<Map<String, Object>> rows = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement(sql);
setParams(pst,params);
rs = pst.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int colCount = metaData.getColumnCount();
while (rs.next()){
Map<String,Object> map = new HashMap<>();
for(int i=1;i<=colCount;i++){
String colName = metaData.getColumnLabel(i);
Object colVal = rs.getObject(i);
map.put(colName,colVal);
}
rows.add(map);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
closeAll(con,pst,rs);
}
return rows;
}
}
entity
Users.java
package com.yzh70723dao.entity;
/**
* @author: XYT
* @create-date: 2022/7/24 11:47
*/
public class Users {
private Integer userId;
private String userName;
private String passWord;
private String nikeName;
private String sex;
private String phone;
public Users() {
}
public Users(Integer userId, String userName, String passWord, String nikeName, String sex, String phone) {
this.userId = userId;
this.userName = userName;
this.passWord = passWord;
this.nikeName = nikeName;
this.sex = sex;
this.phone = phone;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getNikeName() {
return nikeName;
}
public void setNikeName(String nikeName) {
this.nikeName = nikeName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", nikeName='" + nikeName + '\'' +
", sex='" + sex + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
dao
IUsersDAO.java
package com.yzh70723dao.dao;
import com.yzh70723dao.entity.Users;
//数据访问层用户接口
public interface IUsersDAO { //IUsersDAO I 接口标识 Users 针对表名为Users进行操作 DAO 什么层:数据访问层DAO
//根据用户名和密码查询用户账号
Users getByUserNameAndPassword(String userName,String password);
//根据用户名查询数据,判断用户是否存在
boolean getByUserName(String userName);
//根据手机查询用户,判断手机是否存在
boolean getByPhone(String phone);
//添加用户
int insert(Users users);
}
impl
UsersDAOImpl.java
package com.yzh70723dao.dao.impl;
import com.yzh70723.keqiance.BAO;
import com.yzh70723dao.dao.IUsersDAO;
import com.yzh70723dao.entity.Users;
import java.util.List;
import java.util.Map;
/**数据访问层实现类
* @author: XYT
* @create-date: 2022/7/24 12:24
*/
public class UsersDAOImpl implements IUsersDAO { //实现接口 然后Alt+Insert @Override接口的方法
//根据用户名和密码,查帐号
@Override
public Users getByUserNameAndPassword(String userName, String password) {
String sql="select userId,userName,password,nikeName,sex,phone"+
" from users"+
" where userName=? and password=?";
Object[] params={userName,password};
//System.out.println(sql);
List<Map<String, Object>> rows=BAO.exeucteQuery(sql,params); //BAO类文件是复制过来的,如果修改的话,原文件也要修改。
if(rows.size()>0){
//获取集合中的第一条
Map<String,Object> map=rows.get(0);
//将Map中的数据,转为User对象
Users users=new Users();
users.setUserId((Integer) map.get("userId")); //强转
users.setUserName((String) map.get("userName"));
users.setPassWord((String) map.get("password"));
users.setNikeName((String) map.get("nikeName"));
users.setSex((String) map.get("sex"));
users.setPhone((String) map.get("phone"));
return users;
}
//账号密码不正确,返回空
return null;
}
//校验用户名是否存在
@Override
public boolean getByUserName(String userName) {
String sql="select userId,userName,password,nikeName,sex,phone"+
" from users"+
" where userName=?";
Object[] params={userName};
List<Map<String, Object>> rows=BAO.exeucteQuery(sql,params);
return rows.size()>0;
}
//校验手机号是否存在
@Override
public boolean getByPhone(String phone) {
String sql="select userId,userName,password,nikeName,sex,phone"+
" from users"+
" where phone=?";
Object[] params={phone};
List<Map<String, Object>> rows=BAO.exeucteQuery(sql,params);
return rows.size()>0;
}
//插入数据
@Override
public int insert(Users users) {
String sql="insert into users"+
" (userName,password,nikeName,sex,phone)"+
" values"+
" (?,?,?,?,?)";
Object[] params={users.getUserName(),
users.getPassWord(),
users.getNikeName(),
users.getSex(),
users.getPhone()
};
return BAO.executeUpdate(sql,params);
}
}
service
IUsersService.java
package com.yzh70723dao.service;
//定义用户业务层接口
public interface IUsersService {
//用户登录
boolean login();
//用户注册
boolean regist();
}
impl
UsersService.java
package com.yzh70723dao.service.impl;
import com.mysql.cj.util.StringUtils;
import com.yzh70723dao.dao.IUsersDAO;
import com.yzh70723dao.dao.impl.UsersDAOImpl;
import com.yzh70723dao.entity.Users;
import com.yzh70723dao.service.IUsersService;
import java.util.Scanner;
/**用户业务的实现类
* @author: XYT
* @create-date: 2022/7/24 18:21
*/
public class UsersService implements IUsersService {
//用户登录
@Override
public boolean login() {
//输入账号和密码
Scanner scanner=new Scanner(System.in);
System.out.println("please input userName:");
String userName=scanner.next();
System.out.println("please input password:");
String password=scanner.next();
//校验账号和密码是否为空
if(StringUtils.isNullOrEmpty(userName.trim())){
System.out.println("userName cann't be null!");
return false;
}
if(StringUtils.isNullOrEmpty(password.trim())){
System.out.println("password cann't be null!");
return false;
}
//不为空,则校验是否在数据库中存在
IUsersDAO usersDAO=new UsersDAOImpl();
Users users=usersDAO.getByUserNameAndPassword(userName,password);
if(users==null){
System.out.println("userName and password aren't right!");
return false;
}
System.out.println("login sucessifully!");
return true;
}
//用户注册
@Override
public boolean regist() {
//输入信息
Scanner scanner=new Scanner(System.in);
System.out.println("please input userName:");
String userName=scanner.next();
System.out.println("please input password:");
String password=scanner.next();
System.out.println("please input nikeName:");
String nikeName=scanner.next();
System.out.println("please input sex:");
String sex=scanner.next();
System.out.println("please input phone:");
String phone=scanner.next();
//校验
if(StringUtils.isNullOrEmpty(userName.trim())){
System.out.println("userName cann't be null!");
return false;
}
if(StringUtils.isNullOrEmpty(password.trim())){
System.out.println("password cann't be null!");
return false;
}
if(StringUtils.isNullOrEmpty(nikeName.trim())){
System.out.println("nikeName cann't be null!");
return false;
}
if(StringUtils.isNullOrEmpty(sex.trim())){
System.out.println("sex cann't be null!");
return false;
}
if(StringUtils.isNullOrEmpty(phone.trim())){
System.out.println("phone cann't be null!");
return false;
}
//唯一性判断 (待完善,其他的列唯一性判断)
IUsersDAO usersDAO=new UsersDAOImpl(); //上面的步骤也存在,可以定义到外围做全局变量(待完善)
if(usersDAO.getByUserName(userName)){
System.out.println("The userName has already exised!");
return false;
}
if(usersDAO.getByUserName(phone)){
System.out.println("The phone has already exised!");
return false;
}
//插入数据,完成注册
Users users=new Users();
users.setUserName(userName);
users.setPassWord(password);
users.setNikeName(nikeName);
users.setSex(sex);
users.setPhone(phone);
//使用数据访问层插入数据
int count=usersDAO.insert(users);
if(count==1){
System.out.println("logist successfully!");
return true;
}
System.out.println("logist falsely!");
return false;
}
}
APP
package com.yzh70723dao.app;
import com.yzh70723dao.service.IUsersService;
import com.yzh70723dao.service.impl.UsersService;
import java.util.Scanner;
/**
* @author: XYT
* @create-date: 2022/7/24 11:52
*/
public class App {
//模仿入口页面
public static void main(String[] args) {
System.out.println("==============");
System.out.println("Welcome to Tushuguanlisystem.");
System.out.println("==============");
Scanner scanner=new Scanner(System.in);
while(true){
System.out.println("Please choose:1.denglu 2.zhuce 3.tuichu");
int choose=scanner.nextInt();
IUsersService iUsersService=new UsersService();
switch (choose){
case 1:
System.out.println("you choose denglu...");
//IUsersService iUsersService=new UsersService(); //定义到外围(待完善)
boolean isLoginSuc=iUsersService.login();
if(isLoginSuc){
System.out.println("come into system of tushuguanli...");
}
break;
case 2:
System.out.println("you choose zhuce...");
boolean isRegistSuc=iUsersService.regist();
// if(isRegistSuc){
// System.out.println("come into system of tushuguanli...");
// }
break;
case 3:
System.out.println("you choose tuichu...");
break;
default:
System.out.println("you choose false...");
break;
}
}
}
}
课前测 0725
创建表student
#学生表:编号,姓名,性别,生日。
create table student
(
stuId int primary key auto_increment,
stuName varchar(20),
sex varchar(20),
birthday date
);
select * from student;
添加jar包
项目代码
util
BAO.java
package com.yzh70725keqiance.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author: XYT
* @create-date: 2022/7/23 9:01
*/
public class BAO {
private static String driver="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/70723_db1?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
private static String user="root";
private static String password="123456";
public static Connection getConnection(){
Connection con=null;
try {
Class.forName(driver);
con= DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return con;
}
public static void closeAll(Connection con, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void setParams(PreparedStatement pst,Object[] params){
if(params==null){
return;
}
//设置参数
for (int i = 0; i < params.length; i++) {
try {
pst.setObject(i+1,params[i]);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static int executeUpdate(String sql, Object[] params){
Connection con=null;
PreparedStatement pst=null;
int res=-1;
try {
con=getConnection();
pst=con.prepareStatement(sql);
setParams(pst,params);
res=pst.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
closeAll(con,pst,null);
}
return res;
}
public static List<Map<String, Object>> exeucteQuery(String sql,Object[] params){
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<Map<String, Object>> rows = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement(sql);
setParams(pst,params);
rs = pst.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int colCount = metaData.getColumnCount();
while (rs.next()){
Map<String,Object> map = new HashMap<>();
for(int i=1;i<=colCount;i++){
String colName = metaData.getColumnLabel(i);
Object colVal = rs.getObject(i);
map.put(colName,colVal);
}
rows.add(map);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
closeAll(con,pst,rs);
}
return rows;
}
}
entity
Student.java
package com.yzh70725keqiance.entity;
import java.sql.Date;
/**
* @author: XYT
* @create-date: 2022/7/25 9:04
*/
public class Student {
private Integer stuId;
private String stuName;
private String sex;
private Date birthday;
public Student() {
}
public Student(Integer stuId, String stuName, String sex, Date birthday) {
this.stuId = stuId;
this.stuName = stuName;
this.sex = sex;
this.birthday = birthday;
}
public Student(String stuName, String sex, Date birthday) { //方便使用
this.stuName = stuName;
this.sex = sex;
this.birthday = birthday;
}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", sex='" + sex + '\'' +
", birthday='" + birthday + '\'' +
'}';
}
}
dao
IStudentDAO.java
package com.yzh70725keqiance.dao;
import com.yzh70725keqiance.entity.Student;
import java.util.List;
import java.util.Map;
public interface IStudentDAO {
List<Map<String, Object>> query();
int insert(Student student);
int delect(Student student);
int update(Student student);
}
impl
StudentDAO.java
package com.yzh70725keqiance.dao.impl;
import com.yzh70725keqiance.dao.IStudentDAO;
import com.yzh70725keqiance.entity.Student;
import com.yzh70725keqiance.util.BAO;
import java.util.List;
import java.util.Map;
/**
* @author: XYT
* @create-date: 2022/7/25 9:07
*/
public class StudentDAO implements IStudentDAO {
@Override
public List<Map<String, Object>> query() {
String sql = "select * from student ";
System.out.println(sql);
return BAO.exeucteQuery(sql,null);
}
@Override
public int insert(Student student) {
String sql="insert into student"+
" (stuName,sex,birthday)"+
" values"+
" (?,?,?)";
Object[] params={student.getStuName(),
student.getSex(),
student.getBirthday()
};
return BAO.executeUpdate(sql,params);
}
@Override
public int delect(Student student) {
String sql="delete from student"+
" where stuId=? ";
Object[] params={student.getStuId()
};
return BAO.executeUpdate(sql,params);
}
@Override
public int update(Student student) {
String sql="update student"+
" set stuName=?,sex=?,birthday=?"+
" where stuId=?";
Object[] params={
student.getStuName(),
student.getSex(),
student.getBirthday(),
student.getStuId()
};
return BAO.executeUpdate(sql,params);
}
}
service
IStudentService.java
package com.yzh70725keqiance.service;
import com.yzh70725keqiance.entity.Student;
import java.util.List;
import java.util.Map;
public interface IStudentService {
List<Map<String, Object>> sqery();
int insert(Student student);
int delect(Student student);
int update(Student student);
}
impl
StudentService.java
package com.yzh70725keqiance.service.impl;
import com.yzh70725keqiance.dao.IStudentDAO;
import com.yzh70725keqiance.dao.impl.StudentDAO;
import com.yzh70725keqiance.entity.Student;
import com.yzh70725keqiance.service.IStudentService;
import java.util.List;
import java.util.Map;
/**
* @author: XYT
* @create-date: 2022/7/25 9:09
*/
public class StudentService implements IStudentService {
IStudentDAO studentDAO=new StudentDAO();
@Override
public List<Map<String, Object>> sqery() {
return studentDAO.query();
}
@Override
public int insert(Student student) {
return studentDAO.insert(student);
}
@Override
public int delect(Student student) {
return studentDAO.delect(student);
}
@Override
public int update(Student student) {
return studentDAO.update(student);
}
}
app
App
package com.yzh70725keqiance.app;
import com.yzh70725keqiance.entity.Student;
import com.yzh70725keqiance.service.IStudentService;
import com.yzh70725keqiance.service.impl.StudentService;
import java.util.List;
import java.util.Map;
/**
* @author: XYT
* @create-date: 2022/7/25 9:10
*/
public class App {
//模仿入口页面
public static void main(String[] args) {
IStudentService iStudentService=new StudentService();
//插入
// Student student=new Student("zhangsan","nan",java.sql.Date.valueOf("2000-01-01"));
// iStudentService.insert(student);
// Student student2=new Student("lisi","nv",java.sql.Date.valueOf("2002-02-02"));
// iStudentService.insert(student2);
//插入(带有记录数)
// Student student=new Student("zhangsan","nan",java.sql.Date.valueOf("2000-01-01"));
// int res=iStudentService.insert(student);
// System.out.println("jilushu:"+res);
//
//
// Student student2=new Student("lisi","nv",java.sql.Date.valueOf("2002-02-02"));
// int res1=iStudentService.insert(student2);
// System.out.println("jilushu:"+res1);
//修改
Student student3=new Student(1,"zhangsanfeng","nan",java.sql.Date.valueOf("2001-01-01"));
int res=iStudentService.update(student3);
System.out.println("jilushu:"+res); //该输出可有可无,但可以帮助我们理解代码的运行
//Student student4=new Student();
// Student student = new Student(1,"zhangsanfeng","nan",java.sql.Date.valueOf("2001-01-01"));
// //改
// int res = iStudentService.update(student);
// System.out.println("记录数:"+res);
//删除
// int res = iStudentService.delect(student);
// System.out.println("记录数:"+res);
//查找
// List<Map<String, Object>> maps = iStudentService.sqery();
// //System.out.println(maps);
// for (Map map :maps){
// System.out.println(map);
}
}
运行结果
生成表:
插入:
修改:
查找:
删除:
练习2.自从生成代码
package com.yzh70725.zidongshengcheng;
/**
* @author: XYT
* @create-date: 2022/7/25 15:01
*/
public class CodeGenUtil {
//根据数据库获取java类型
public static String getJavaType(String dbType){
if("varchar".equalsIgnoreCase(dbType) ||
"char".equalsIgnoreCase(dbType)){
return "String";
} else if ("double".equalsIgnoreCase(dbType)||
"float".equalsIgnoreCase(dbType)||
"decimal".equalsIgnoreCase(dbType)) {
return "double";
} else if ("int".equalsIgnoreCase(dbType)) {
return "int";
} else if ("date".equalsIgnoreCase(dbType)) {
return "date";
}
return null;
}
}
package com.yzh70725.zidongshengcheng;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.*;
/**
* @author: XYT
* @create-date: 2022/7/25 15:15
*/
public class Test {
public static void main(String[] args) {
Connection con=null;
PreparedStatement pst=null;
ResultSet rs=null;
String tabName="student";
String sql="select * from "+tabName+" where 1<>1 "; //什么意思?
try {
con=BAO.getConnection();
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
//获取结果集对象
ResultSetMetaData metaData=rs.getMetaData();
int colCount=metaData.getColumnCount();
//public StringBuilder append(Object obj) { return append(String.valueOf(obj)); }
StringBuilder strJavaEntity = new StringBuilder();
strJavaEntity.append("public class "+tabName+"{\r\n");
//获取每一列的信息
for(int i=1;i<=colCount;i++){
String colName = metaData.getColumnName(i);
String colType= metaData.getColumnTypeName(i);
strJavaEntity.append("\tprivate "+CodeGenUtil.getJavaType(colType)+" "+colName+";\r\n");
}
strJavaEntity.append("}");
System.out.println(strJavaEntity);
//打印java类内容到磁盘文件
PrintWriter out=new PrintWriter("D:/"+tabName+".java");
out.println(strJavaEntity);
out.flush();
out.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
BAO.closeAll(con,pst,rs);
}
}
}
练习3.log4j的使用(日志工具)
package com.yzh70725.jilu;
import org.apache.log4j.Logger;
/**
* @author: XYT
* @create-date: 2022/7/25 12:00
*/
public class Test1 {
public static void main(String[] args) {
//创建记录对象
Logger logger=Logger.getLogger(Test1.class);
//debug<info<warn<error<fatal 级别
logger.debug("This is the message of debug");
logger.info("This is the message of info");
logger.warn("This is the message of warn");
logger.error("This is the message of error");
logger.fatal("This is the message of fatal");
}
}
package com.yzh70725.jilu;
import com.yzh70725.zidongshengcheng.Test;
import org.apache.log4j.Logger;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @author: XYT
* @create-date: 2022/7/25 12:02
*/
public class Test2 {
public static void main(String[] args) {
Logger logger=Logger.getLogger(Test2.class);
logger.debug("Project start!");
Scanner scanner=new Scanner(System.in);
try {
logger.debug("Be ready to input a number"); //debug
System.out.println("Please input a number:");
int num1=scanner.nextInt();
logger.info("The first number:"+num1); //info
logger.debug("Be ready to input another number");
System.out.println("Please input another number:");
int num2=scanner.nextInt();
logger.info("The second number:"+num2);
logger.debug("Being preparing to ruturn result:");
int res=num1/num2;
logger.info("The resule is:"+res);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
} catch (ArithmeticException exception) {
logger.error("ERROR:ArithmeticException!"+exception.getMessage()); //发生了数学运算异常
exception.printStackTrace();
} catch (InputMismatchException exception) {
logger.error("ERROR:InputMismatchException!"+exception.getMessage()); //发生了输入不匹配异常
exception.printStackTrace();
}
logger.debug("The project over!");
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118092.html