java-JDBC增删改查 详细流程

 

写增删改查的流程

  1. 先写数据库 JavaBean
  2. 导jar包   jdbc工具类   jdbc.properties
  3. 注册驱动
  4. 获取连接
  5. 定义sql
  6. 预编译
  7. 传参(给预编译的问号传参)
  8. 执行sql  (查询是) 
    executeQuery 执行命令
  9. 查询是最好实例化 javabean  然后用ArrayList集合  把数据add  最后输出集合 
  10. 增删改 都使用 
    executeUpdate 执行更新
  11. 最后记得释放资源 
url=jdbc:mysql:///数据库名
user=root  mysql账号
password=root   mysql密码  -- 账号密码安装时候设置的
driver=com.mysql.jdbc.Driver  

对象的调用流程:JSP—Service—DAO—Hibernate(某框架)—数据库。

domain层,通常就是用于放置这个系统中,与数据库中的表,一一对应起来的JavaBean的

Student类

package Sudent.domain;

public class Student {
    private String id; //学号
    private String name; //姓名
    private String sex; // 性别
    private int age; //年龄
    private String specialty;//专业
    private String telephone;//电话

    public Student() {
    }

    public Student(String id, String name, String sex, int age, String specialty, String telephone) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.specialty = specialty;
        this.telephone = telephone;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    public String getSpecialty() {
        return specialty;
    }

    public void setSpecialty(String specialty) {
        this.specialty = specialty;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }


    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", specialty='" + specialty + '\'' +
                ", telephone='" + telephone + '\'' +
                '}';
    }
}

DAO(Data Access Object) 是数据访问层

StudentDao

package Sudent.dao;

import Sudent.domain.Student;

public interface StudentDao {
    /**
     * 学生表操作的dao
     * @return
     */

    int add(Student student);

    /**
     * 根据学号删除
     * @return
     */
    int DeleteById(String id);


    /**
     * 根据学号修改年龄
     * @return
     */
    int UpdateByID(int age,String id);


    /**
     * 根据学号查询学生信息
     * @return
     */
    Student SelectById(String id);

}

studnetDaoImpl类

package Sudent.dao;

import Sudent.domain.Student;
import Sudent.util.JDBCUtils;


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

public class StudentDaoImpl implements StudentDao {

    /**
     * 添加学生数据
     * @param
     * @return
     */
    @Override
    public int add(Student student) {
        Connection conn = null;
        PreparedStatement pstm = null;
        int count = 0;

        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = JDBCUtils.getConnection();
            //3.定义sql
            String sql = "insert into student(id,NAME,sex,age,specialty,telephone)value (?,?,?,?,?,?)";
            //预编译sql  防注入
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, student.getId());
            pstm.setString(2, student.getName());
            pstm.setString(3, student.getSex());
            pstm.setInt(4, student.getAge());
            pstm.setString(5, student.getSpecialty());
            pstm.setString(6, student.getTelephone());

            count = pstm.executeUpdate();
            System.out.println("成功插入" + count  +"条信息");


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            JDBCUtils.close(null,pstm,conn);
        }
        return count;
    }

    @Override
    public int DeleteById(String id) {
        Connection conn = null;
        PreparedStatement pstm = null;
        int count = 0;

        try {
            //获取连接
            conn = JDBCUtils.getConnection();
            //定义sql
            String sql = "delete from student where id = ?";
            //预编译
            pstm = conn.prepareStatement(sql);
            pstm.setString(1,id);
            //调用sql
            count = pstm.executeUpdate();


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return count;
    }

    @Override
    public int UpdateByID(int age,String id) {
        Connection conn = null;
        PreparedStatement pstm = null;
        int count = 0;
        try {

            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = JDBCUtils.getConnection();
            String sql = "update student set age = ? where id = ?";
            pstm = conn.prepareStatement(sql);
            //传入值
            pstm.setInt(1,age);
            pstm.setString(2,id);
            //执行sql
            count = pstm.executeUpdate();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(null,pstm,conn);
        }

        return count;
    }


    @Override
    public Student SelectById(String id) {
        Connection conn = null;
        PreparedStatement pstm = null;

        Student st = null;

        try {

            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = JDBCUtils.getConnection();
            String sql = "select * from student where id = ?";
            pstm = conn.prepareStatement(sql);
            //传入值
            pstm.setString(1,id);
            //执行sql
            ResultSet rs = pstm.executeQuery();

            ArrayList list = new ArrayList<>();
            while(rs.next()){
                st = new Student();
                st.setId(rs.getString("id"));
                st.setName(rs.getString("name"));
                st.setSex(rs.getString("sex"));
                st.setAge(rs.getInt("age"));
                st.setSpecialty(rs.getString("specialty"));
                st.setTelephone(rs.getString("telephone"));
                list.add(st);
            }
            //输出集合
            System.out.println(list);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(null,pstm,conn);
        }


        return st;
    }


}

JDBCUtil工具类

package Sudent.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {

    //声明三个成员变量
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /**
     * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
     */
    static{
        //读取资源文件,获取值。
        try {
            //1.创建Properties集合类。
            Properties pro = new Properties();

            //获取src路径下的文件的方式-->>ClassLoader:类加载器
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL res = classLoader.getResource("jdbc.properties");
            String path = res.getPath();
            //System.out.println(path);
            //2.加载文件
            //pro.load(new FileReader("G:\\JavaWeb\\JDBC\\JDBCday04\\day04_jdbc\\src\\jdbc.properties"));
            pro.load(new FileReader(path));
            //3.获取属性赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            //4.注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接
     * @return 连接对象
     */

    public static Connection getConnection() throws SQLException {
        //return null;
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(Statement stmt,Connection conn){
        if( stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 重载
     * @param rs
     * @param
     * @param conn
     */
    public static void close(ResultSet rs, PreparedStatement pstm, Connection conn){
        if( rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (pstm != null){
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

service层:service层叫服务层,被称为服务,肯定是相比之下比较高层次的一层结构,相当于将几种操作封装起来

我这里算不上封装 ~  

package Sudent.service;

import Sudent.dao.StudentDao;
import Sudent.dao.StudentDaoImpl;
import Sudent.domain.Student;

import java.util.Scanner;

public class StudentService {

    public static void main(String[] args) {

        //添加学生信息
        Student student = new Student();//学生数据数理化
        StudentDao stuImpl = new StudentDaoImpl();//增删改查实例化
        Scanner sc = new Scanner(System.in);

//        System.out.println("添加学生数据-->按照以下提示输入");
//        System.out.println("请输入学号:");
//        String id = sc.next();//ID
//        System.out.println("请输入姓名:");
//        String name = sc.next();//姓名
//        System.out.println("请输入性别:");
//        String sex = sc.next();//性别
//        System.out.println("请输入年龄:");
//        int age = sc.nextInt();//年龄
//        System.out.println("请输入专业:");
//        String specialty  = sc.next();//专业
//        System.out.println("请输入联系方式:");
//        String telephone = sc.next();//电话
//
//        student.setId(id);
//        student.setName(name);
//        student.setSex(sex);
//        student.setAge(age);
//        student.setSpecialty(specialty);
//        student.setTelephone(telephone);
//
//        stuImpl.add(student);//调用
//
//        System.out.println("添加成功");
//        sc.close();

        /*
        //根据学号删除学生
        System.out.println("根据id删除该学生");
        System.out.println("请输入学号:");
        String ID = sc.next();//ID
        student.setId(ID);
        stuImpl.DeleteById(ID);
        System.out.println("删除成功");
        */



        //根据学生学号修改信息(修改年龄)

        /*
        System.out.println("根据学号修改该学生年龄");
        System.out.println("请输入要学号:");
        String Uid = sc.next();
        System.out.println("请输入修改后的年龄:");
        int age = sc.nextInt();

        student.setAge(age);
        student.setId(Uid);
        stuImpl.UpdateByID(age,Uid);
        System.out.println("修改成功");
        */


        //根据学号查询学生信息
        System.out.println("请输入学号查询学生信息");
        String id = sc.next();
        stuImpl.SelectById(id);



    }

}

建立数据库

CREATE TABLE Student(
id VARCHAR(50), 
NAME VARCHAR(32),
sex VARCHAR(10),
age INT(10),
specialty VARCHAR(32), -- 专业
telephone VARCHAR(50)			
)

SELECT * FROM Student;
-- 给学生表添加数据
INSERT INTO student(id,NAME,sex,age,specialty,telephone)VALUE('FY2020Java0101','张三','女',20,'软件技术','15290915016');

DELETE FROM student WHERE id = ?; -- 删除
UPDATE student SET age = ? WHERE id = ? -- 根据id修改年龄
SELECT * FROM student WHERE id = ?; -- 根据id查询该学生信息

 

有几个注意的点:

  1. StudentDao接口里面写的增删改查用传参的形式   方便后面在service封装  
  2. template方法简单的 写的代码会更少 
  3. 使用prepareStatement   预编译  防止sql注入 
  4. 调用的时候记得new 学生类 
  5. 接口类  对象名 = new 接口实现类    

你可能感兴趣的:(java)