学习JDBC记录

一、JDBC(java数据库连接)

在这里插入图片描述
在这里插入图片描述

1、JDBC的功能

  1. 连接数据库
  2. 执行SQL语句
  3. 获得SQL语句的查询结果

2、SQL语句基本知识

(1)、DBMS(数据库管理系统)

查看当前实例下包含多少个数据库:show databases;

注意:分号一定要有

删除指定的数据库:drop database 数据库名;
创建新的数据库:create database [IF NOT EXISTS] 数据库名;
进入指定数据库:use 数据库名
查询该数据库下包含了多少数据表:show tables;
查看指定数据表的表结构(如表的列数、每列的数据类型):desc 表名
运行mysql命令,用于连接远程主机的MySQL服务:mysql -p 密码 -u 用户名 -h 主机名

(2)、SQL语句

查询语句:select
数据操作语言:insert update delete
数据定义语言:create(创建) alter(修改) drop(删除) truncate
数据控制语言:grant revoke
事务控制语句:commit rollback savepoint

(3)、约束

非空约束:NOT NULL
唯一约束:UNIQUE
主键:PRIMARY KEY
外键:FOREIGN KEY
检查:CHECK

二、JDBC的用法

1、组成JDBC API 的接口和类

(1)、DriverManager类:

作用:获取Connection对象
方法:public static Connection getConnection(String url,String user,String pass)

(2)、Connection接口:

作用:获得数据库连接,访问数据库
方法:Statement createStatement() PreparedStatement prepareStatement(String sql) CallableStatement prepaerCall(String sql);

(3)、Statement接口:

作用:执行SQL语句的工具接口
方法:
执行查询语句ResultSet executeQuery(String sql)
执行DML语句int executeUpate(String sql)
执行SQL语句boolean execute()

(4)、PreparedStatement接口:
(5)、ResultSet结果集对象

2、JDBC编程

(1)、加载数据库驱动Class.forName(driverClass)
例如,加载MySQL驱动:Class.forName(com.mysql.jdbc.Driver)
(2)、通过DriverManager获取数据库连接DriverManager.getConnection(String url,String user,String password)三个参数分别是数据库URL,登录数据库的用户名和密码,例如MySQL数据库URL的写法:jdbc:mysql://localhost:3306/databasename
(3)、通过Connection对象创建Statement对象,方法:
①createStatement():创建基本的statement对象 ②prepareStatement(String sql)根据传入的SQL语句创建预编译的statement对象 ③prepareCall(String sql)
(4)、使用Statement执行SQL语句,方法:①execute() ②executeUpdate() ③executeQuery():执行查询语句

(5)、操作结果集,返回ResultSet()对象,方法①移动记录指针:next等②获取记录指针值getXxx()
(6)、回收数据库资源,关闭ResultSet,Statement,Connection等资源
使用finally来关闭数据库资源

JDBC测试:

package com.cxq.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBC {
    public static void main(String[] args) throws Exception {
        /*
        * 1、注册驱动,加载驱动
        * */
        Class.forName("com.mysql.cj.jdbc.Driver");
        /*
        * 2、获取连接
        * */
        String url="jdbc:mysql://localhost:3306/companydb";
        String username="root";
        String password="184548";
       Connection connection= DriverManager.getConnection(url,username,password);
       if (connection!=null){
           System.out.println("连接到数据库啦");
       }else {
           System.out.println("连接失败");
       }
       /*
       * 3、获得执行SQL语句的对象
       * */
        Statement  statement=connection.createStatement();
        /*
        * 4、编写SQL语句,执行SQL语句
        * */
        String sql="insert into t_jobs(job_id,job_title,min_salary,max_salary) values ('python_1','pythonee','1000','9000')";
        int result=statement.executeUpdate(sql);
        System.out.println(result);
        /*
        * 5、处理接收结果
        * */
        if (result==1){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        /*
        * 6、释放资源:先开后关
        * */
        statement.close();
        connection.close();
    }
}

运行结果:
在这里插入图片描述

综合案例,实现删除一条记录的操作

  • 核心代码
package com.cxq.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DeleteJDBC {
    public static void main(String[] args) throws Exception {
        /*注册驱动,加载驱动*/
        Class.forName("com.mysql.cj.jdbc.Driver");
        /*获取连接*/
        String url="jdbc:mysql://localhost:3306/companydb";
        String username="root";
        String password="184548";
        Connection connection=DriverManager.getConnection(url,username,password);
        /*获取执行SQL语句的对象*/
        Statement statement=connection.createStatement();
        /*编写SQL语句,执行SQL语句*/
        int result=statement.executeUpdate("delete from t_jobs where job_id='java_1'");
        /*处理结果*/
        if (result==1){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
        /*释放资源*/
        statement.close();
        connection.close();
    }
}

运行结果:
在这里插入图片描述

ResultSet结果集的遍历

  • 核心代码
package com.cxq.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class QueryJDBC {
    public static void main(String[] args) throws Exception {
        /*1:加载驱动*/
        Class.forName("com.mysql.cj.jdbc.Driver");
        /*2:获取连接*/
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb","root","184548");
        /*3:获取执行SQL语句的对象*/
        Statement statement=connection.createStatement();
        /*4:执行SQL语句,接收结果*/
        ResultSet resultSet=statement.executeQuery("select * from t_jobs");
        /*5:处理结果*/
        while (resultSet.next()){//仅仅是判断下一行是否有数据
            //对当前每行每列的数据进行获取 根据列的编号
            String job_id=resultSet.getString(1);
            String job_title=resultSet.getString(2);
            String min_salary=resultSet.getString(3);
            String max_salary=resultSet.getString(4);
            System.out.println(job_id+"\t"+job_title+"\t"+min_salary+"\t"+max_salary);
        }
        /*6:释放资源*/
        resultSet.close();
        statement.close();
        connection.close();
    }
}

  • 执行结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

此处为根据编号获得,下面为根据列名获得
将第五步处理结果出代码修改为:执行结果是一样的

 /*5:处理结果*/
        while (resultSet.next()){
            String job_id=resultSet.getString("job_id");
            String job_title=resultSet.getString("job_title");
            String min_salary=resultSet.getString("min_salary");
            String max_salary=resultSet.getString("max_salary");
            System.out.println(job_id+"\t"+job_title+"\t"+min_salary+"\t"+max_salary);
        }

登录案例:

  • 核心代码
package com.cxq.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class LoginJDBC {
    public static void main(String[] args) throws Exception{
        /*控制台输入*/
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=scanner.next();
        System.out.println("请输入密码:");
        String password=scanner.next();
        /*1:加载驱动*/
        Class.forName("com.mysql.cj.jdbc.Driver");
        /*2:获取连接*/
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb","root","184548");
        /*3:获得对象*/
        Statement statement=connection.createStatement();
        /*4:执行SQL语句*/
        ResultSet resultSet=statement.executeQuery("select *  from users where username='"+username+"'and password='"+password+"'");
        /*5:处理结果*/
        if (resultSet.next()){
            System.out.println("查询到了");
        }else{
            System.out.println("查询失败");
        }

        /*6:关闭连接*/
        resultSet.close();
        statement.close();
        connection.createStatement();
    }
}

  • 运行结果:

在这里插入图片描述

PreparedStatement和ResultSet的相关应用

在这里插入图片描述

在这里插入图片描述

封装工具类:

package com.cxq.JDBC;

import java.sql.*;

/*
* 重用性方案
* 获取连接
* 释放资源
* */
public class DBUtils {
    static{//类加载,只执行一次
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /*1:获取连接*/
    public static Connection getConnection(){

        Connection connection= null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb","root","184548");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }
    /*2:释放资源*/
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (statement!=null){
                statement.close();
            }
            if (connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

跨平台方案

1:配置文件
在这里插入图片描述
2:工具类

package com.cxq.jdbc2;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    /*给一个私有的静态的常量*/
    private static final Properties properties=new Properties();//存储配置文件的map
    static{
        /*通过流连接到properties文件*/
        InputStream is=DBUtils.class.getResourceAsStream("/db.properties");
        /*通过load方法将流读取进来*/
        try {
            properties.load(is);//通过流将配置文件内容加载到properties集合
            Class.forName(properties.getProperty("driver"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        Connection connection= null;
        try {
            connection = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username"),properties.getProperty("password"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }
    public static void closeAll(Connection connection, Statement statement,ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

四、Dao层和Druid连接池

Dao:数据访问对象,实现了业务逻辑和数据库访问相分离

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
一、创建数据表
在这里插入图片描述
在这里插入图片描述
二、创建DBUtils工具类

  • 代码位置:

src\com\cxq\person\DBUtils.java

package com.cxq.person;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    /*私有静态常量*/
    private static final Properties PROPERTIES=new Properties();
    /*静态代码块*/
    static{
        /*字节输入流*/
        InputStream is=DBUtils.class.getResourceAsStream("/db.properties");
        try {
            /*通过PROPERTIES的load的方法将is的流的内容加载进来*/
            PROPERTIES.load(is);
            /*加载驱动,获得连接*/
            Class.forName(PROPERTIES.getProperty("driver"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /*提供一个静态方法,返回值类型为Connection的方法,获得连接*/
    public static Connection getConnection(){
        /*1:创建一个Connection*/
        Connection connection=null;
        /*2:获得连接*/
        try {
            connection= DriverManager.getConnection(PROPERTIES.getProperty("url"),PROPERTIES.getProperty("username"),PROPERTIES.getProperty("password"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return connection;
        /*最后:返回一个Connection*/
    }
    /*关闭连接*/
    public static void closeAll(Connection connection, Statement statement,ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (statement!=null){
                statement.close();
            }
            if (connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

三、创建实体类
在这里插入图片描述

  • 代码位置

:com.cxq.person.Person

package com.cxq.person;

import java.util.Date;

public class Person {
    private Integer id;
    private String name;
    private Integer age;
    private Date bornDate;
    private String email;
    private String address;

    public Person() {
    }

    public Person(Integer id, String name, Integer age, Date bornDate, String email, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.bornDate = bornDate;
        this.email = email;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", bornDate=" + bornDate +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBornDate() {
        return bornDate;
    }

    public void setBornDate(Date bornDate) {
        this.bornDate = bornDate;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

三、Dao层
在这里插入图片描述

  • 代码位置:com.cxq.person.PersonDaoImpl.java
    增删查改各功能实现情况
    在这里插入图片描述

新增方法如下:
在这里插入图片描述
测试新增:

  • 代码位置

:com.cxq.person.TestPerson
代码:

package com.cxq.person;
/*测试类*/
public class TestPerson {
    public static void main(String[] args) {
        //测试新增,调用PersonDaoImpl里面的insert方法来新增功能
        PersonDaoImpl personDao=new PersonDaoImpl();
        /*new一个person对象 id自动增长,所以要把id去掉*/
        Person person=new Person("Gavin",18,null,"Gavin@163.com","北京市");
        /*将person传入insert方法*/
        int result=personDao.insert(person);
        if (result==1){
            System.out.println("新增成功");
        }else{
            System.out.println("新增失败");
        }
    }
}

运行结果:在这里插入图片描述
在这里插入图片描述
修改功能:

 /*修改 做修改的person传入的是id*/
    public int update(Person person){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql="update person set name=?,age=?,borndate=?,email=?,address=? where id=?";
        try {
            /*先获取连接*/
            connection=DBUtils.getConnection();
            /*再进行预编译sql语句*/
            preparedStatement=connection.prepareStatement(sql);
            /*占位符的赋值*/
            preparedStatement.setString(1,person.getName());
            preparedStatement.setInt(2,person.getAge());
            preparedStatement.setDate(3,null);
            preparedStatement.setString(4,person.getEmail());
            preparedStatement.setString(5,person.getAddress());
            preparedStatement.setInt(6,person.getId());
            /*执行sql语句,并且接收结果*/
            int result=preparedStatement.executeUpdate();
            return result;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtils.closeAll(connection,preparedStatement,null);
        }
        return 0;}

测试修改:

package com.cxq.person;

public class TestPersonUpdate {
    public static void main(String[] args) {
        /*测试修改,调用update方法*/
        PersonDaoImpl personDao=new PersonDaoImpl();
        Person person=new Person(1,"Cxq",20,null,"Cxq@vip.com","天津市");
        int result=personDao.update(person);
       if (result==1){
           System.out.println("修改成功");
       }else {
           System.out.println("修改失败");
       }
    }
}

删除功能:

 /*删除 指定他的id就可以删除用户的信息*/
    public int delete(int id){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql="delete from person where id=?";
        /*先获取连接*/
        connection=DBUtils.getConnection();
        /*再预编译sql语句*/
        try {
            preparedStatement=connection.prepareStatement(sql);
            /*为问号?占位符赋值*/
            preparedStatement.setInt(1,id);
            /*执行删除*/
            int result=preparedStatement.executeUpdate();
            /*将结果直接返回给调用者*/
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtils.closeAll(connection,preparedStatement,null);
        }
        return 0;}

测试删除:

package com.cxq.person;

public class TestPersonDelete {
    public static void main(String[] args) {
        /*测试删除,需要调用PersonDaoImpl的delete方法*/
        PersonDaoImpl personDao=new PersonDaoImpl();
        /*不用创建对象,直接调用删除方法*/
        int result=personDao.delete(2);
        if (result==1){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }
}

查询单个功能:

 /*查单个 @Param 根据id查询用户信息*/
    public Person select(int id){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        /*1:SQL语句*/
        String sql="select * from person where id=?;";
        Person person=null;
        try {
            /*2:获取连接*/
            connection=DBUtils.getConnection();
            /*3:预编译SQL语句*/
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            /*5:接收结果*/
            resultSet=preparedStatement.executeQuery();
            if (resultSet.next()){/*如果查到下一行有数据*/
                person=new Person();
                /*要查询的所有信息项目:6个列*/
                int pid=resultSet.getInt("id");
                String name=resultSet.getString("name");
                int age=resultSet.getInt("age");
                Date bornDate=resultSet.getDate("borndate");
                String email=resultSet.getString("email");
                String address=resultSet.getString("address");
                /*接着在外面创建一个person对象等于空,然后在里面如果查到了数据,通过new person,将各项通过setXxx()方法放进person里面*/
                person.setId(pid);
                person.setName(name);
                person.setAge(age);
                person.setBornDate(bornDate);
                person.setEmail(email);
                person.setAddress(address);

            }
            /*最后返回person,熟练以后可通过有参数的构造方法来赋值*/
            return  person;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            /*关闭所有用到的连接*/
            DBUtils.closeAll(connection,preparedStatement,resultSet);
        }
        return null;}

测试查询单个:

package com.cxq.person;
/*测试类:查询*/
public class TestPersonSelect {
    public static void main(String[] args) {
        /*要用到PersonDaoImpl的查询单个方法*/
        PersonDaoImpl personDao=new PersonDaoImpl();
        Person person=personDao.select(6);
        if (person!=null){
            /*直接打印他的toString方法*/
            System.out.println(person);
        }else {
            System.out.println("没有查到该用户");
        }
    }
}

查询所有功能:

/*查所有 返回的是一个list集合*/
    public List<Person> selectAll(){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        Person person=null;
        /*查询所有,结果放到一个list集合里*/
        List<Person> personList=new ArrayList<>();

        try {
            /*获取连接*/
            connection=DBUtils.getConnection();
            /*预编译SQL语句*/
            preparedStatement=connection.prepareStatement("select * from person;");/*查询所有是没有条件的*/
            /*接收结果*/
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){/*因为查询到的结果是一个多行多列的数据,所以用循环来做*/
                int pid=resultSet.getInt("id");
                String name=resultSet.getString("name");
                int age=resultSet.getInt("age");
                Date bornDate=resultSet.getDate("borndate");
                String email=resultSet.getString("email");
                String address=resultSet.getString("address");
                /*先new一个对象 初始化*/
                person =new Person(pid,name,age,bornDate,email,address);
                /*往集合里面添加*/
                personList.add(person);
            }
            return personList;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;}

测试查询所有功能:

package com.cxq.person;

import java.util.List;

public class TestPersonSelectAll {
    public static void main(String[] args) {
        PersonDaoImpl personDao=new PersonDaoImpl();
        /*返回的是一个集合*/
        /*接收*/
        List<Person> personList=personDao.selectAll();
        /*通过for方法做遍历,每拿到一个,就打印他的tostring方法*/
        for (Person p : personList) {
            System.out.println(p);
        }
    }
}

Service层:

在这里插入图片描述
在这里插入图片描述
案例:
一:新建数据库表
在这里插入图片描述
在这里插入图片描述
1:新建包-》数据库连接工具类书写
在这里插入图片描述

package com.cxq.account;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    /*私有静态常量*/
    private static final Properties PROPERTIES=new Properties();
    /*静态代码块*/
    static{
        /*字节输入流*/
        InputStream is=DBUtils.class.getResourceAsStream("/db.properties");
        try {
            /*通过PROPERTIES的load的方法将is的流的内容加载进来*/
            PROPERTIES.load(is);
            /*加载驱动,获得连接*/
            Class.forName(PROPERTIES.getProperty("driver"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /*提供一个静态方法,返回值类型为Connection的方法,获得连接*/
    public static Connection getConnection(){
        /*1:创建一个Connection*/
        Connection connection=null;
        /*2:获得连接*/
        try {
            connection= DriverManager.getConnection(PROPERTIES.getProperty("url"),PROPERTIES.getProperty("username"),PROPERTIES.getProperty("password"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return connection;
        /*最后:返回一个Connection*/
    }
    /*关闭连接:遵循先开后关原则*/
    public static void closeAll(Connection connection, PreparedStatement preparedStatement,ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (preparedStatement!=null){
                preparedStatement.close();
            }
            if (connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

2:新建实体类-》提供get set 有参数 无参数构造方法以及toString方法
在这里插入图片描述

package com.cxq.account;

public class Account {
    private String cardNo;
    private String password;
    private String name;
    private double balance;

    public Account() {
    }

    public Account(String cardNo, String password, String name, double balance) {
        this.cardNo = cardNo;
        this.password = password;
        this.name = name;
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "cardNo='" + cardNo + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", balance=" + balance +
                '}';
    }

    public String getCardNo() {
        return cardNo;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

3:Dao层封装操作(增删查改方法)
在这里插入图片描述

package com.cxq.account;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountDaoImpl {
    /*此处是增 删 查 改各方法*/
    public int insert(Account account){
        return 0;
    }
    /*删除*/
    public int delete(String  cardNo){
        return 0;
    }
    /*修改*/
    public int update(Account account){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql="update account set password=?,name=?,balance=? where cardNo=?;";
        try {
            /*连接*/
            connection=DBUtils.getConnection();
            /*预编译SQL语句*/
            preparedStatement=connection.prepareStatement(sql);
            /*3:占位符的赋值*/
            preparedStatement.setString(1,account.getPassword());/*第一个存的是密码*/
            preparedStatement.setString(2,account.getName());
            preparedStatement.setDouble(3,account.getBalance());/*第三个存的是余额*/
            preparedStatement.setString(4,account.getCardNo());
            /*用result接收修改 返回result即可*/
            int result=preparedStatement.executeUpdate();
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            /*关闭所有连接*/
            DBUtils.closeAll(connection,preparedStatement,null);
        }
        return 0;
    }
    /*查询单个
    * @Param 根据唯一标识cardNo来查询
    * */
    public Account select(String cardNo){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        Account account=null;
        /*SQL语句*/
        String sql="select * from account where cardNo=?;";
        try {
            /*获取连接*/
            connection=DBUtils.getConnection();
            /*预编译sql语句*/
            preparedStatement=connection.prepareStatement(sql);
            /*为占位符赋值*/
            preparedStatement.setString(1,cardNo);
            /*处理查询结果并接收*/
            resultSet=preparedStatement.executeQuery();
            /*拿到一行数据*/
            if (resultSet.next()){
                //本行有数据
                String cardNos=resultSet.getString("cardNo");/*拿到四个属性*/
                String password=resultSet.getString("password");
                String name=resultSet.getString("name");
                double balance=resultSet.getDouble("balance");
                account =new Account(cardNo,password,name,balance);
            }
            return account;/*返回account账户*/
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            /*关闭连接*/
            DBUtils.closeAll(connection,preparedStatement,resultSet);
        }

        return null;
    }
}

4:service业务逻辑层
在这里插入图片描述

package com.cxq.account;

public class AccountServiceImpl {
    /*转账功能
    * @Param 账户 密码 对方账户 转账金额*/
    public void transfer(String fromNo,String pwd,String toNo,double money){/*收参*/
        AccountDaoImpl accountDao=new AccountDaoImpl();
        try {
            /*2:组织完善业务功能*/
            /*2.1验证fromNo是否存在*/
            /*调用dao的select方法*/
            Account account=accountDao.select(fromNo);
            if (account==null){
                /*该账户为空 抛出异常,*/
                throw new RuntimeException("卡号不存在");
            }
            /*2.2验证fromNo的密码是否正确*/
            /*如果查到了,判断:如果查到的密码和输入的密码不一致,任然是抛出异常*/
            if (!account.getPassword().equals(pwd)){
                throw new RuntimeException("密码错误");
            }
            /*2.3验证余额是否充足*/
            /*如果卡里的金额小于输入的要转账的金额*/
            if (account.getBalance()<money){
                throw new RuntimeException("余额不足");
            }
            /*2.4验证toNo是否存在*/
            Account toAccount=accountDao.select(toNo);
            if (toAccount==null){
                throw new RuntimeException("对方卡号不存在");
            }
            /*2.5减少fromNo的余额*/
            /*改变卡里余额*/
            account.setBalance(account.getBalance()-money);
            accountDao.update(account);
            /*2.6增加toNo的余额*/
            toAccount.setBalance(toAccount.getBalance()+money);
            accountDao.update(toAccount);
            System.out.println("转账成功");
        } catch (RuntimeException e) {
            System.out.println("转账失败");
            e.printStackTrace();
        }
    }
}

5:测试在这里插入图片描述

package com.cxq.account;

public class TestAccount {
    public static void main(String[] args) {
        /*需要用到业务逻辑层的转账功能*/
        AccountServiceImpl accountService=new AccountServiceImpl();
        accountService.transfer("6002","1234","6003",1000);
    }
    
}

数据库连接池的常用参数

  1. 数据库的初始连接数
  2. 连接池的最大连接数
  3. 连接池的最小连接数
  4. 连接池的每次增加的容量
    表示方法:javax.sql.DataSource
    DBCP数据源:使用DBCP来获得数据库连接的方式
  • 1、创建数据源对象BasicDataSource ds=new BasicDataSource();
  • 2、设置连接池所需要的的驱动ds.setDriverClassName("com.mysql.jdbc.Driver")
  • 3、设置连接数据库的URLds.setUrl("jdbc:mysql://localhost:3306/javaee")
  • 4、设置连接数据库的用户名ds.setUsername("root")
  • 5、连接数据库的密码ds.setPassword("password")
  • 6、设置连接池的初始连接数ds.setInitialSize(5)
  • 7、设置连接池最多可以有多少个活动连接ds.setMaxActive(20)
  • 8、设置连接池中最小有2个空闲连接ds.setMinIdle(2)
  • 9、通过数据源获取连接Connection conn=ds.getConnection();
  • 10、释放数据库连接conn.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
系统根据B/S,即所谓的电脑浏览器/网络服务器方式,运用Java技术性,挑选MySQL作为后台系统。系统主要包含对客服聊天管理、字典表管理、公告信息管理、金融工具管理、金融工具收藏管理、金融工具银行卡管理、借款管理、理财产品管理、理财产品收藏管理、理财产品银行卡管理、理财银行卡信息管理、银行卡管理、存款管理、银行卡记录管理、取款管理、转账管理、用户管理、员工管理等功能模块。 文中重点介绍了银行管理的专业技术发展背景和发展状况,随后遵照软件传统式研发流程,最先挑选适用思维和语言软件开发平台,依据需求分析报告模块和设计数据库结构,再根据系统功能模块的设计制作系统功能模块图、流程表和E-R图。随后设计架构以及编写代码,并实现系统能模块。最终基本完成系统检测和功能测试。结果显示,该系统能够实现所需要的作用,工作状态没有明显缺陷。 系统登录功能是程序必不可少的功能,在登录页面必填的数据有两项,一项就是账号,另一项数据就是密码,当管理员正确填写并提交这二者数据之后,管理员就可以进入系统后台功能操作区。进入银行卡列表,管理员可以进行查看列表、模糊搜索以及相关维护等操作。用户进入系统可以查看公告和模糊搜索公告信息、也可以进行公告维护操作。理财产品管理页面,管理员可以进行查看列表、模糊搜索以及相关维护等操作。产品类型管理页面,此页面提供给管理员的功能有:新增产品类型,修改产品类型,删除产品类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值