JDBC的基础以及利用注解和配置文件实现代码的复用

JDBC的快速入门

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

public class JDBCdemo01 {
    public static void main(String[] args) throws Exception {
        //1.导入驱动jar包
        //2.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //3.获取对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root");
        //创建sql语句
        String Sql="update stu set age=18 where id=1";
        //获取使用sql语句的对象statement
        Statement statement = connection.createStatement();
        int i = statement.executeUpdate(Sql);
        System.out.println(i);
        statement.close();
        connection.close();
    }
}

JDBC实现摘要中的需求

数据库中的数据:
在这里插入图片描述

为提高代码的复用性,采用自定义工具类进行代码的抽取,为不改变工具类的代码实现使用不同数据库或者不同类型数据库的连接使用注解和配置文件两种不同的方式实现同一需求演示

一、注解的方式:
自定义注解类:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JDBC {
    public abstract String url();
    public abstract String user();
    public abstract String password();
    public abstract String driver();

}

工具类:

import java.sql.*;

@JDBC(url = "jdbc:mysql:///db1",user = "root",password = "root",driver = "com.mysql.jdbc.Driver")
public class JDBCUTIL {
     private static String url = null;
     private static String user =null;
     private static String password = null;
     private static String driver = null;

    private static void JDBCAlotation(){
        //解析注解
        Class<JDBCUTIL> jdbcutilClass = JDBCUTIL.class;
        JDBC annotation = jdbcutilClass.getAnnotation(JDBC.class);
        //获取对应的注解属性
         url = annotation.url();
         user = annotation.user();
         password = annotation.password();
         driver = annotation.driver();
    }



    //静态代码块

    static {
        //执行静态方法
        JDBCAlotation();
        try {
            //加载配置文件
            Class aClass = Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection jdbcUtilGetConnection() throws SQLException {
        //注册信息
            return DriverManager.getConnection(url, user, password);
    }
    //释放资源
    public void jdbcUtilClose(Connection connection , Statement statement){
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    //释放资源方法的重载形式
    public void jdbcUtilClose(ResultSet resultSet, Connection connection , Statement statement){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

测试类:

import org.w3c.dom.ls.LSOutput;

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

//需求:将数据库中的数据存放到一个类对象中
public class JDBCTEST5 {
    public static void main(String[] args) {
        //在外面创建对象避免重复多次创建同一个对象
        stu stu1=null;
        List<stu> list=new ArrayList<>();
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        JDBCUTIL jdbcutil=new JDBCUTIL();
        try {
            /*//注册
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接对象
             connection = DriverManager.getConnection("jdbc:mysql:///db1", "root", "root");*/
            Connection connection1 = jdbcutil.jdbcUtilGetConnection();
            //书写查询语句
            String sql="select * from stu";
            //获取statemate执行对象
             statement = connection1.createStatement();
             resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                int id=resultSet.getInt("id");
                String name=resultSet.getString("name");
                int age=resultSet.getInt("age");
                double source=resultSet.getDouble("source");
                Date birthday=resultSet.getDate("birthday");
                Date insert_time=resultSet.getDate("insert_time");

                //创建stu对象获取数据
                 stu1=new stu();
                 stu1.setId(id);
                 stu1.setName(name);
                 stu1.setAge(age);
                 stu1.setSource(source);
                 stu1.setBirthday(birthday);
                 stu1.setInsert_time(insert_time);
                //创建结合存储数据
                list.add(stu1);
            }
            list.stream().forEach(s-> System.out.println(s));
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
           jdbcutil.jdbcUtilClose(resultSet, null,statement);
        }
    }
}

运行结果:
在这里插入图片描述
二、配置文件的方式
1.配置文件:

url = jdbc:mysql:///db1
user = root
password = root
driver = com.mysql.jdbc.Driver

2.工具类:

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

public class JDBCUTIL2 {
    private static String url=null;
    private static String user=null;
    private static String password=null;
    private static String driver=null;


    public static void JDBCUTIL(){
        Properties properties=new Properties();
        //获取类加载器
        ClassLoader classLoader = JDBCUTIL2.class.getClassLoader();
        //获取对应的配置文件的地址返回流信息
        InputStream resourceAsStream = classLoader.getResourceAsStream("JDBCUTIL.properties");
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

         url = properties.getProperty("url");
         user = properties.getProperty("user");
         password = properties.getProperty("password");
         driver =  properties.getProperty("driver");
    }

    static {
        JDBCUTIL();
        try {
            //加载文件进内存
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public Connection jdbcUtilGetConnection() throws SQLException {
        //注册
        return  DriverManager.getConnection(url,user,password);
    }

    //释放资源
    public void jdbcUtilClose(Connection connection , Statement statement){
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    //释放资源方法的重载形式
    public void jdbcUtilClose(ResultSet resultSet, Connection connection , Statement statement){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

测试类:(因第二个工具类与第一个工具类中的方法名称一致所以测试类只需修改创建对象的名称的一行代码)

import org.w3c.dom.ls.LSOutput;

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

//需求:将数据库中的数据存放到一个类对象中
public class JDBCTEST5 {
    public static void main(String[] args) {
        //在外面创建对象避免重复多次创建同一个对象
        stu stu1=null;
        List<stu> list=new ArrayList<>();
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        JDBCUTIL2 jdbcutil=new JDBCUTIL2();
        try {
            /*//注册
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接对象
             connection = DriverManager.getConnection("jdbc:mysql:///db1", "root", "root");*/
            Connection connection1 = jdbcutil.jdbcUtilGetConnection();
            //书写查询语句
            String sql="select * from stu";
            //获取statemate执行对象
             statement = connection1.createStatement();
             resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                int id=resultSet.getInt("id");
                String name=resultSet.getString("name");
                int age=resultSet.getInt("age");
                double source=resultSet.getDouble("source");
                Date birthday=resultSet.getDate("birthday");
                Date insert_time=resultSet.getDate("insert_time");

                //创建stu对象获取数据
                 stu1=new stu();
                 stu1.setId(id);
                 stu1.setName(name);
                 stu1.setAge(age);
                 stu1.setSource(source);
                 stu1.setBirthday(birthday);
                 stu1.setInsert_time(insert_time);
                //创建结合存储数据
                list.add(stu1);
            }
            list.stream().forEach(s-> System.out.println(s));
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
           jdbcutil.jdbcUtilClose(resultSet, null,statement);
        }
    }
}

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值