一、目录结构

二、代码

1、domain/Emp

package JDBC.domain;

import java.util.Date;

public class Emp {
    //private int id;
    private Integer id;
    private String ename;
    //private int job_id;
    //private int mgr;
    private Integer job_id;
    private Integer mgr;
    private Date joindate;
    //private double salary;
    //private double bonus;
    private Double salary;
    private Double bonus;
    //private int dept_id;
    private Integer dept_id;

    public Integer getId() {
        return id;
    }

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

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public Integer getJob_id() {
        return job_id;
    }

    public void setJob_id(Integer job_id) {
        this.job_id = job_id;
    }

    public Integer getMgr() {
        return mgr;
    }

    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }

    public Date getJoindate() {
        return joindate;
    }

    public void setJoindate(Date joindate) {
        this.joindate = joindate;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Double getBonus() {
        return bonus;
    }

    public void setBonus(Double bonus) {
        this.bonus = bonus;
    }

    public Integer getDept_id() {
        return dept_id;
    }

    public void setDept_id(Integer dept_id) {
        this.dept_id = dept_id;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", ename='" + ename + '\'' +
                ", job_id=" + job_id +
                ", mgr=" + mgr +
                ", joindate=" + joindate +
                ", salary=" + salary +
                ", bonus=" + bonus +
                ", dept_id=" + dept_id +
                '}';
    }
}
View Code

2、Utils/JDBCUtils

package JDBC.Utils;

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

public class JDBCUtils {
    private static String url;
    private static String password;
    private static String user;
    private static String driver;

    static {
        try {
            Properties pro = new Properties();
            //ClassLoader加载器
            /*ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL res = classLoader.getResource("jdbc.properties");
            String path = res.getPath();
            System.out.println(path);
            pro.load(new FileReader(path));*/
            pro.load(new FileReader("D:\\IdeaProjects\\basic-code\\test\\src\\JDBC\\jdbc.properties"));

            url = pro.getProperty("url");
            password = pro.getProperty("password");
            user = pro.getProperty("user");
            driver = pro.getProperty("driver");

            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

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

    public static void Close(Statement stmt, Connection conn){
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void Close(ResultSet rs,Statement stmt, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
View Code

3、Utils/JDBCUtils_druid

package JDBC.Utils;
//连接池的工具类

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JDBCUtils_druid {
    private static DataSource ds;
    static {
        try {
            Properties pro = new Properties();
            //pro.load(JDBCUtils_druid.class.getResourceAsStream("druid.properties"));
            pro.load(new FileReader("D:\\IdeaProjects\\basic-code\\test\\src\\JDBC\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //释放资源
    public static void Close(Statement stmt,Connection conn){
        Close(null,stmt,conn);
    }
    //重载
    public static void Close(ResultSet rs,Statement stmt, Connection conn){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //获取连接池
    public static DataSource getDataSource() {
        return ds;
    }
}
View Code

4、JDBC_demo1

package JDBC;

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

public class JDBC_demo1 {
    public static void main(String[] args) throws Exception{
        //创建驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //获取数据库连接对象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","123456");
        //定义sql语句
        String sql = "update account set balance = 500 where id = 1";
        //获取sql对象Statement
        Statement stmt = conn.createStatement();
        //执行sql
        int count = stmt.executeUpdate(sql);
        //处理结果
        System.out.println(count);
        //释放资源
        conn.close();
        stmt.close();
    }
}
View Code

5、JDBC_demo2

package JDBC;

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

public class JDBC_demo2 {
    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //String sql = "insert into account values(null,'wangwu',2000)";
            //String sql = "update account set balance = 1500 where id = 3";
            String sql = "delete from account where id = 3";
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","123456");
            stmt = conn.createStatement();
            int count = stmt.executeUpdate(sql);
            System.out.println(count);
            if (count>0){
                System.out.println("成功!");
            }else{
                System.out.println("失败!");
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
View Code

6、JDBC_demo3

package JDBC;

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

public class JDBC_demo3 {
    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //String sql = "insert into account values(null,'wangwu',2000)";
            //String sql = "update account set balance = 1500 where id = 3";
            //String sql = "delete from account where id = 3";
            String sql = "create table student(id int,name varchar(20))";
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","123456");
            stmt = conn.createStatement();
            int count = stmt.executeUpdate(sql);
            System.out.println(count);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
View Code

7、JDBC_demo4

package JDBC;

import java.sql.*;

public class JDBC_demo4 {
    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String sql = "select * from account";
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","123456");
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()){
                int id = rs.getInt(1);
                String name = rs.getString("name");
                double balance = rs.getDouble(3);
                System.out.println(id+"--"+name+"--"+balance);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
View Code

8、JDBC_demo5

package JDBC;

import JDBC.domain.Emp;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBC_demo5 {
    public static void main(String[] args) {
        List<Emp> list = new JDBC_demo5().findALL();
        System.out.println(list);
        System.out.println(list.size());
    }

    public List<Emp> findALL(){
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        List<Emp> list = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","123456");
            String sql = "select * from emp";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            Emp emp = null;
            list = new ArrayList<Emp>();
            while(rs.next()){
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");
                emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                list.add(emp);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return list;
    }
}
View Code

9、JDBC_demo6

package JDBC;
//工具类
import JDBC.Utils.JDBCUtils;
import JDBC.domain.Emp;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBC_demo6 {
    public static void main(String[] args) {
        List<Emp> list = new JDBC_demo6().findALL();
        System.out.println(list);
        System.out.println(list.size());
    }

    public List<Emp> findALL(){
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        List<Emp> list = null;
        try {
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","123456");
            conn = JDBCUtils.getConnection();
            String sql = "select * from emp";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            Emp emp = null;
            list = new ArrayList<Emp>();
            while(rs.next()){
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");
                emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                list.add(emp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
           JDBCUtils.Close(rs,stmt,conn);
        }
        return list;
    }
}
View Code

10、JDBC_demo7

package JDBC;

import JDBC.Utils.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

/**
 * 练习:
 *         * 需求:
 *             1. 通过键盘录入用户名和密码
 *             2. 判断用户是否登录成功
 */
public class JDBC_demo7 {

    public static void main(String[] args) {
        //键盘录入,接受用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();
        //2.调用方法
        boolean flag = new JDBC_demo7().login(username, password);
        //3.判断结果,输出不同语句
        if(flag){
            //登录成功
            System.out.println("登录成功!");
        }else{
            System.out.println("用户名或密码错误!");
        }
    }
    //登录方法(使用PreparedStatement实现,防止sql注入问题)
    public boolean login(String username ,String password){
        if(username == null || password == null){
            return false;
        }
        //连接数据库判断是否登录成功
        Connection conn = null;
        PreparedStatement pstmt =  null;
        ResultSet rs = null;
        //获取连接
        try {
            conn =  JDBCUtils.getConnection();
            //定义sql
            String sql = "select * from user where username = ? and password = ?";
            //获取执行sql的对象
            pstmt = conn.prepareStatement(sql);
            //赋值
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //执行查询(无需传参)
            rs = pstmt.executeQuery();
            //判断
           return rs.next();//如果有下一行,则返回true

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.Close(rs,pstmt,conn);
        }

        return false;
    }
}
View Code

11、JDBC_demo8

package JDBC;

import JDBC.Utils.JDBCUtils;

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

public class JDBC_demo8 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);//开启事务
            String sql1 = "update account set balance = balance + ? where id = ?";
            String sql2 = "update account set balance = balance - ? where id = ?";
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            pstmt1.setDouble(1,500);
            pstmt1.setDouble(2,1);
            pstmt2.setInt(1,500);
            pstmt2.setInt(2,2);
            pstmt1.executeUpdate();
            int i = 3/0;//手动制造异常
            pstmt2.executeUpdate();
            conn.commit();//提交事务
        } catch (Exception e1) {
            try {
                if (conn!=null){
                    conn.rollback();//回滚事务
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
            e1.printStackTrace();
        } finally {
            JDBCUtils.Close(pstmt1,conn);
            JDBCUtils.Close(pstmt2,null);
        }
    }
}
View Code

12、C3P0_demo

package JDBC;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class C3P0_demo {//连接池
    public static void main(String[] args) throws SQLException {
        //DataSource ds = new ComboPooledDataSource();//获取默认配置
        DataSource ds = new ComboPooledDataSource("otherc3p0");//获取指定配置
        for (int i = 1; i <=8 ; i++) {
            Connection conn = ds.getConnection();
            System.out.println(i+":"+conn);
            if (i==4){
                conn.close();//归还
            }
        }
    }
}
View Code

13、druid_demo1

package JDBC;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class druid_demo1 {
    public static void main(String[] args) throws Exception {
        Properties pro = new Properties();
        InputStream is = druid_demo1.class.getClassLoader().getResourceAsStream("JDBC/druid.properties");
        pro.load(is);
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }
}
View Code

14、druid_demo2

package JDBC;

import JDBC.Utils.JDBCUtils_druid;

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

public class druid_demo2 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils_druid.getConnection();
            String sql = "insert into account values(null,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"wangwu");
            pstmt.setDouble(2,3000);
            int count = pstmt.executeUpdate();
            System.out.println(count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils_druid.Close(pstmt,conn);
        }
    }
}
View Code

15、JDBC_template1

package JDBC;

import JDBC.Utils.JDBCUtils_druid;
import org.springframework.jdbc.core.JdbcTemplate;

public class JDBC_template1 {
    public static void main(String[] args) {
        JdbcTemplate template= new JdbcTemplate(JDBCUtils_druid.getDataSource());
        String sql = "update account set balance=5000 where id = ?";
        int count = template.update(sql,3);
        System.out.println(count);
    }
}
View Code

16、JDBC_template2

package JDBC;


import JDBC.Utils.JDBCUtils_druid;
import JDBC.domain.Emp;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JDBC_template2 {
    public static void main(String[] args) {

    }
    private JdbcTemplate template= new JdbcTemplate(JDBCUtils_druid.getDataSource());
    /*Junit单元测试,可以让方法独立执行*/
    //1.修改1号数据salary为10000
    @Test
    public void test1(){
        String sql = "update emp set salary=10000 where id = 1";
        int count = template.update(sql);
        System.out.println(count);
    }
    //2.添加一条记录
    @Test
    public void test2(){
        String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
        int count = template.update(sql,3,"郭靖",10);
        System.out.println(count);
    }
    //3.删除刚才添加的记录
    @Test
    public void test3(){
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 3);
        System.out.println(count);
    }
    //4.查询id为1的记录,将其封装为Map集合.注意:这个方法查询的结果集长度只能是1
    @Test
    public void test4(){
        String sql = "select * from emp where id = ?";
        Map<String,Object> map = template.queryForMap(sql,1);
        System.out.println(map);
    }
    //5. 查询所有记录,将其封装为List
    @Test
    public void test5(){
        String sql = "select * from emp";
        List<Map<String,Object>> lists = template.queryForList(sql);
        for(Map<String,Object> list:lists){
            System.out.println(list);
        }
    }
    //6. 查询所有记录,将其封装为Emp对象的List集合
    @Test
    public void test6_1(){
        String sql = "select * from emp";
        List<Emp> lists = template.query(sql, new RowMapper<Emp>() {
            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                return emp;
            }
        });
        for (Emp emp : lists) {
            System.out.println(emp);
        }
    }
    //6. 查询所有记录,将其封装为Emp对象的List集合(简化)
    @Test
    public void test6_2(){
        String sql = "select * from emp";
        List<Emp> lists = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : lists) {
            System.out.println(emp);
        }
    }
    //7. 查询总记录数
    @Test
    public void test7(){
        String sql = "select count(id) from emp";
        Long total = template.queryForObject(sql,Long.class);
        System.out.println(total);
    }
}
View Code

 

posted on 2020-11-13 20:08  晨曦生辉耀匕尖  阅读(7)  评论(0编辑  收藏  举报