day05 数据库增删改查

1 配置文件

#这是一个数据库配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.110:3306/db01?&useSSL=false//去掉ssl警告
jdbc.username=root
jdbc.password=123456

2 连接池类

package com.yuxhu.jdbcTask;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;

public class DBUtilPool {
    static String driver;
    static String url;
    static String username;
    static String password;
    static BasicDataSource bds;
    //静态加载
    static{
        String accountConfig = "com/yuxhu/config/account.properties";
        Properties pro = new Properties();
        try {
            //加载外面配置文件
            pro.load(DBUtilPool.class.getClassLoader().getResourceAsStream(accountConfig));
            driver = pro.getProperty("jdbc.driver");
            url = pro.getProperty("jdbc.url");
            username = pro.getProperty("jdbc.username");
            password = pro.getProperty("jdbc.password");
            //建立连接池
            bds = new BasicDataSource();
            bds.setDriverClassName(driver);
            bds.setUrl(url);
            bds.setUsername(username);
            bds.setPassword(password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection(){
        Connection conn = null;
        if(bds == null){
            System.out.println("连接池为空!");
            return null;
        }
        try {
            conn = bds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //关闭连接
    public static void closeConnection(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

3 定义接口以及接口实现类

package com.yuxhu.jdbcTask;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public interface FunctionInterface {
    public boolean Login(String username, String password); //登陆
    public boolean Add(String username, String password);//增加用户
    public boolean Delete(String username);//删除用户
    public boolean modify(String option, String username, String newName);//修改用户
    public boolean search(String username);//查找用户
}

class Function implements FunctionInterface{
    Connection conn;
    PreparedStatement ps;
    
    // 登陆
    public boolean Login(String username, String password) {
        // 连接池拿连接
        conn = DBUtilPool.getConnection();
        // 准备好的声明
        ps = null;
        boolean result = false;

        String sql = "select username, password from account where username = ?";

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);

            // 执行声明
            ResultSet rs = ps.executeQuery();

            // 判断是否有查询那结果
            if (rs.next()) {
                if (!(rs.getString(2).equals(password))) {
                    System.out.println("密码错误,请重新登陆!");
                    result = false;
                }else{
                    System.out.println("登陆成功,请输入你的操作选项:");
                    result = true;
                }
            }else {
                System.out.println("账号错误,请重新登陆!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 关闭
        finally {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DBUtilPool.closeConnection(conn);
        }
        return result;
    }
    
    
    // 增加用户
    @Override
    public boolean Add(String username, String password) {
        // 连接池拿连接
        conn = DBUtilPool.getConnection();
        // 准备好的声明
        ps = null;
        boolean result = false;

        String sql = "insert into account (username, password) value ( ? , ? )";

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);

            try {
                // 执行声明
                int rs = ps.executeUpdate();

                // 判断是否有查询那结果
                if (rs != 0) {
                    result = true;
                    System.out.println("添加用户成功");
                } else {
                    throw new SQLException();
                }

            } catch (SQLException e) {
                System.out.println("用户名已存在,添加失败,请重试");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 关闭
        finally {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DBUtilPool.closeConnection(conn);
        }
        return result;
    }
    // 删除用户
    @Override
    public boolean Delete(String username) {
        if(username.equals("adm")){
            System.out.println("不能删除管理员!");
            return false;
        }
        // 连接池拿连接
        conn = DBUtilPool.getConnection();
        // 准备好的声明
        ps = null;
        boolean result = false;
        
        try {
            String sql = null;
            if(!(username.equals("all"))){
                sql = "delete from account where username = ?";
                ps = conn.prepareStatement(sql);
                ps.setString(1, username);
            }else if(username.equals("all")){
                sql = "delete from account where username <> ?";
                ps = conn.prepareStatement(sql);
                ps.setString(1, "adm");
            }
            
            try {
                // 执行声明
                int rs = ps.executeUpdate();

                // 判断是否有查询那结果
                if (rs != 0) {
                    result = true;
                    System.out.println("删除用户成功");
                } else {
                    throw new SQLException();
                }

            } catch (SQLException e) {
                System.out.println("用户名不存在,删除失败,请重试");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 关闭
        finally {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DBUtilPool.closeConnection(conn);
        }
        return result;
    }
    
    // 修改用户
    @Override
    public boolean modify(String option, String username, String newName) {
        // 连接池拿连接
        conn = DBUtilPool.getConnection();
        // 准备好的声明
        ps = null;
        boolean result = false;
        
        //判断用户名是否存在
        String exist = "select username from account where username = ?";
        try {
            ps = conn.prepareStatement(exist);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if(!(rs.next())){
                System.out.println("要修改的用户名不存在! 请重试");
                return false;
            }
            ps.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        String sql = null;
        String msg = null;
        if (option.equals("1")) {
            sql = "update account set username = ? where username = ?";
            msg = "修改用户名成功!";
        }
        if (option.equals("2")) {
            sql = "update account set password = ? where username = ?";
            msg = "修改密码成功!";
        }

        if (sql != null) {
            try {
                ps = conn.prepareStatement(sql);
                ps.setString(1, newName);
                ps.setString(2, username);
                try {
                    // 执行声明
                    int rs = ps.executeUpdate();

                    // 判断是否有查询那结果
                    if (rs != 0) {
                        result = true;
                        System.out.println(msg);
                    }
                } catch (SQLException e) {
                    System.out.println("新用户名重名,修改失败,请重试");
                }

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 关闭
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtilPool.closeConnection(conn);

        return result;
    }
    //查找用户
    @Override
    public boolean search(String username) {
        boolean result = false;
        conn = DBUtilPool.getConnection();
        String sql = "select username, password from account where username like ?";
        try {
            if(username.equals("all")){
                username = "%";
            }
            ps = conn.prepareStatement(sql);
            ps.setString(1, username + "%");
            ResultSet rs = ps.executeQuery();

            if(!(rs.next())){
                System.out.println("没有找到此用户!请重试!");
                return false;
            }else{
                rs.previous();
                System.out.println("你查看的用户信息如下:");
            }

            while (rs.next()) {
                System.out.println("用户名:" + rs.getString(1) + "\t密码:" + rs.getString(2));
                result = true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 关闭
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtilPool.closeConnection(conn);
        return result;
    }
}

4 测试

package com.yuxhu.jdbcTask;

import java.util.Scanner;

public class LoginRegister {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Function fun = new Function();
        
        boolean result = false;
        while(!result){
            System.out.println("账号:");
            String username = input.nextLine();
            System.out.println("密码:");
            String password = input.nextLine();
            //1.登陆
            result = fun.Login(username, password);
        }
        
        while(result){
            System.out.println("1.增加用户");
            System.out.println("2.删除用户");
            System.out.println("3.修改用户");
            System.out.println("4.查找用户");
            System.out.println("5.退出系统");
            
            String option = input.next();
            
            //增加用户
            if (option.equals("1")) {
                boolean flag = false;
                while (!flag) {
                    System.out.println("请输入要添加的用户名:(main 返回主菜单)");
                    String username = input.next();
                    if(username.equals("main")){
                        break;
                    }
                    System.out.println("请输入要添加的用户名密码:(main 返回主菜单)");
                    String password = input.next();
                    if(password.equals("main")){
                        break;
                    }
                    flag = fun.Add(username, password);
                }
            }
            
            //删除用户
            if(option.equals("2")){
                boolean flag = false;
                while (!flag) {
                    System.out.println("请输入要删除的用户名:(main 返回主菜单, all 删除全部)");
                    String username = input.next();
                    if(username.equals("main")){
                        break;
                    }
                    flag = fun.Delete(username);
                }
            }
            //修改用户  
            if(option.equals("3")){
                boolean flag = false;
                while (!flag) {
                    System.out.println("请输入你要修改的用户名:(main 返回主菜单)");
                    String username = input.next();
                    if(username.equals("main")){
                        break;
                    }
                    System.out.println("请输入你要修改的选项:1.用户名 2.密码 (main 返回主菜单)");
                    String num = input.next();
                    if(num.equals("main")){
                        break;
                    }
                    if(num.equals("1")){
                        System.out.println("请输入新的用户名:(main 返回主菜单)");
                        String newName = input.next();
                        if(newName.equals("main")){
                            break;
                        }
                        flag = fun.modify(num,username,newName);
                    }
                    if(num.equals("2")){
                        System.out.println("请输入新的密码:(main 返回主菜单)");
                        String password = input.next();
                        if(password.equals("main")){
                            break;
                        }
                        flag = fun.modify(num,username,password);
                    }
                }
            }
            //查找用户
            if(option.equals("4")){
                boolean flag = false;
                while(!flag){
                    System.out.println("请输入你要查看的用户名:(all查看全部)");
                    
                    String username = input.next();
                    flag = fun.search(username);
                }
            }
            
            //退出系统
            if(option.equals("5")){
                System.out.println("已退出系统");
                result = false;
            }
        }
        //关闭Scanner
        input.close();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,511评论 6 13
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,367评论 6 343
  • 哦,果然还是挪威的森林呀。 从昨天下午回来一直到今天凌晨,郑州一直处在一个闷热的状态,清晨四点多...
    章鱼丸粗面阅读 156评论 0 0
  • 我的生活好像变得越来越简单了——社交,消费。社交包括和朋友一起聊天玩耍、跟同事沟通工作、与商家确认信息等等。而消费...
    贝尼阅读 577评论 4 4