jdbc使用的具体案例

一、jdbc使用的案例

1.工具类

package com;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

//1.获取连接对象 2.关闭连接对象---取代单元测试中的 @Before 和 @After
public class JdbcUtil {
    
    
    private static Properties p;

    static {
    
    
        //1.读取jdbc.properties文件
        try{
    
    
            FileInputStream is = new FileInputStream("D:\\java0104\\jdbc--day05\\src\\jdbc.properties");
            p = new Properties();
            p.load(is);
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
    //1.获取连接对象
    public static Connection getCon(){
    
    
        try{
    
    
            return DriverManager.getConnection(p.getProperty("url"),p);
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
        return null;
    }
    //2.释放资源
    public static void close(ResultSet rs, Statement state,Connection con){
    
    
        if (rs!=null){
    
    
            try {
    
    
                rs.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
        if (state!=null){
    
    
            try {
    
    
                state.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
        if (con!=null){
    
    
            try {
    
    
                con.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
    
    
        System.out.println(getCon());
    }
}

2.查询一个表中所有的数据,得到一个结果集,封装结果集到list集合,并在控制台输出

package lei;

import java.sql.Date;

public class Emp {
    
    
    private int id;
    private String name;
    private String gender;
    private double salary;
    private Date join_date;
    private int dept_id;

    public Emp() {
    
    
    }

    @Override
    public String toString() {
    
    
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", salary=" + salary +
                ", join_date=" + join_date +
                ", dept_id=" + dept_id +
                '}';
    }

    public Emp(int id, String name, String gender, double salary, Date join_date, int dept_id) {
    
    
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.salary = salary;
        this.join_date = join_date;
        this.dept_id = dept_id;
    }

    public int getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

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

    public String getGender() {
    
    
        return gender;
    }

    public void setGender(String gender) {
    
    
        this.gender = gender;
    }

    public double getSalary() {
    
    
        return salary;
    }

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

    public Date getJoin_date() {
    
    
        return join_date;
    }

    public void setJoin_date(Date join_date) {
    
    
        this.join_date = join_date;
    }

    public int getDept_id() {
    
    
        return dept_id;
    }

    public void setDept_id(int dept_id) {
    
    
        this.dept_id = dept_id;
    }
}
package com;

import lei.Emp;
import org.junit.Before;
import org.junit.Test;

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

public class Hello2 {
    
    
    private Connection con=null;
    private Statement state=null;
    private ResultSet rs=null;
    @Before//获得连接对象
    public void init(){
    
    
        try {
    
    
            //1.注册驱动 Driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.DriverManager获取连接数据库对象
            String url="jdbc:mysql:///db3?useSSL=false&serverTimezone=UTC";
            con= DriverManager.getConnection(url,"root","123456");

        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
    @Test//查询
    public void test1(){
    
    
        try {
    
    
            //1.定义sql
            String sql="select * from emp";
            //2.创建执行sql的对象
            state=con.createStatement();
            //3.执行sql,返回一个结果rs--集合+迭代器
             rs = state.executeQuery(sql);
            ArrayList<Emp> emps = new ArrayList<>();
            while(rs.next()){
    
    
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                double salary = rs.getDouble("salary");
                Date join_date = rs.getDate("join_date");
                int dept_id = rs.getInt("dept_id");
                //调用有参构造
                Emp emp = new Emp(id,name,gender,salary,join_date,dept_id);
                emps.add(emp);
            }
            System.out.println(emps);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            //释放资源
            if (rs!=null){
    
    
                try {
    
    
                    rs.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
            if (state!=null){
    
    
                try {
    
    
                    rs.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
            if (con!=null){
    
    
                try {
    
    
                    rs.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述

3.用statement去实现登录案例

package com;

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

public class Hello1 {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的用户名:");
        String name = sc.nextLine();
        System.out.println("请输入您的密码:");
        String psw = sc.nextLine();
        boolean isLogin=login(name,psw);
        System.out.println(isLogin);
    }
    //登陆方法
    private static boolean login(String name, String psw) {
    
    
        //1.获取连接对象
        Connection con = JdbcUtil.getCon();
        //2.定义sql
        String sql="select * from users where name= '"+name+"' and psw= '"+psw+"'";
        Statement state=null;
        ResultSet rs = null;
        try{
    
    
            //3.获取执行sql的对象
            state = con.createStatement();
            //4.执行sql
            rs=state.executeQuery(sql);
            return rs.next();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            JdbcUtil.close(rs,state,con);
        }
        return false;
    }
}

在这里插入图片描述

4.用子接口preparedstatement去优化登录案例

package com;

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

public class Hello2 {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的用户名:");
        String name = sc.nextLine();
        System.out.println("请输入您的密码:");
        String psw = sc.nextLine();
        boolean isLogin=login2(name,psw);
        System.out.println(isLogin);
    }
    //登陆方法--改进版
    private static boolean login2(String name, String psw) {
    
    
        //1.获取连接对象
        Connection con = JdbcUtil.getCon();
        //2.定义sql
        String sql="select * from users where name= ? and psw= ? ";
        PreparedStatement pstm=null;
        ResultSet rs = null;
        try{
    
    
            //3.获取执行sql的对象
            pstm=con.prepareStatement(sql);
            pstm.setString(1,name);
            pstm.setString(2,psw);
            //4.执行sql
            rs=pstm.executeQuery();
            return rs.next();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            JdbcUtil.close(rs,pstm,con);
        }
        return false;
    }
}

在这里插入图片描述

5.事务–转账案例

package com;

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

public class Hello2 {
    
    
    public static void main(String[] args) {
    
    
        //1.获取连接对象
        Connection con = JdbcUtil.getCon();
        //2.定义sql
        String sql1="update account set balance=balance-? where id=?";
        String sql2="update account set balance=balance+? where id=?";
        PreparedStatement pstm1=null;
        PreparedStatement pstm2=null;
        try {
    
    
            //开启事物--设置手动提交
            con.setAutoCommit(false);

            //3.获取执行sql的对象
            pstm1=con.prepareStatement(sql1);
            pstm2=con.prepareStatement(sql2);
            //4.给占位符赋值
            pstm1.setDouble(1,500);
            pstm1.setInt(2,1);
            pstm2.setDouble(1,500);
            pstm2.setInt(2,2);
            //5.执行sql
            pstm1.executeUpdate();
                int i=6/0;//主动制造异常
            pstm2.executeUpdate();
            //提交事务
            con.commit();
        } catch (SQLException e) {
    
    
            try {
    
    
                //回滚事务
                con.rollback();
            } catch (SQLException ex) {
    
    
                ex.printStackTrace();
            }finally {
    
    
                JdbcUtil.close(null,pstm1,con);
            }
        }
    }
}

总结

以上就是jdbc使用的具体案例的全部内容,主要是利用jdbc连接数据库从而达到实现。

猜你喜欢

转载自blog.csdn.net/StruggleBamboo/article/details/112393128
今日推荐