jdbc工具类

增删改查案例(无工具类)

java 复制代码
import com.fengfeng.domain.Student;

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

/**
 * @Author: fengfeng
 * @Date: 2022/07/24/9:35
 * @Description: 业余爱好者
 */
public class StudentDaoImpl implements StudentDao {
    @Override
    public ArrayList<Student> findAll() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        ArrayList<Student> list = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");

            connection = DriverManager.getConnection("jdbc:mysql://192.168.188.140:3306/db14", "root", "123456");

            statement = connection.createStatement();

            String sql = "select * from student";

            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                Integer sid = resultSet.getInt("sid");
                String name = resultSet.getString("name");
                Integer age = resultSet.getInt("age");
                Date birthday = resultSet.getDate("birthday");

                Student student = new Student(sid, name, age, birthday);

                list.add(student);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return list;
    }

    @Override
    public Student findById(Integer id) {
        Student student = new Student();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.188.140:3306/db14", "root", "123456");
            statement = connection.createStatement();

            String sql = "select * from student where sid='" + id + "'";

            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                Integer sid = resultSet.getInt("sid");
                String name = resultSet.getString("name");
                Integer age = resultSet.getInt("age");
                Date birthday = resultSet.getDate("birthday");

                student.setSid(sid);
                student.setName(name);
                student.setAge(age);
                student.setBirthday(birthday);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return student;
    }

    @Override
    public int insert(Student stu) {
        Connection connection = null;
        Statement statement = null;
        int result = 0;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.188.140:3306/db14", "root", "123456");
            statement = connection.createStatement();

            java.util.Date birthday = stu.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(birthday);
            String sql = " insert into student values ('" + stu.getSid() + "','" + stu.getName() + "','" + stu.getAge() + "','" + format + "')";

            result = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public int update(Student stu) {
        Connection connection = null;
        Statement statement = null;
        int result = 0;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.188.140:3306/db14", "root", "123456");
            statement = connection.createStatement();

            java.util.Date birthday = stu.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(birthday);
            String sql = " update student set sid = '" + stu.getSid() + "' , name = '" + stu.getName() + "', age = '" + stu.getAge() + "' , birthday = '" + birthday + "' where sid = '" + stu.getSid() + "'";

            result = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public int delete(Integer id) {
        Connection connection = null;
        Statement statement = null;
        int result = 0;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.188.140:3306/db14", "root", "123456");
            statement = connection.createStatement();

            String sql = "delete from student where sid='"+id+"' ";

            result = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return result;
    }
}

JDBCUtils(自己写的)

properties 复制代码
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.188.140:3306/db14?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
username=root
password=123456
java 复制代码
/**
 * @Author: fengfeng
 * @Date: 2022/07/24/11:04
 * @Description: 业余爱好者
 */

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

/**
 * jdbc工具类
 */
public class JDBCUtils {
    // 私有化构造方法
    private JDBCUtils() {
    }

    // 声明所需要的配置变量
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection connection;

    // 提供代码块,读取配置文件的信息为变量赋值,注册驱动
    static {
        //读取配置文件的信息为变量赋值

        try {
            InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取数据库连接的方法
    public static Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //提供释放资源的方法
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //提供释放资源的方法
    public static void close(Connection connection, Statement statement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

增删改查案例(有工具类)

java 复制代码
import com.fengfeng.domain.Student;
import com.fengfeng.utils.JDBCUtils;

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

/**
 * @Author: fengfeng
 * @Date: 2022/07/24/9:35
 * @Description: 业余爱好者
 */
public class StudentDaoImpl implements StudentDao {
    @Override
    public ArrayList<Student> findAll() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        ArrayList<Student> list = new ArrayList<>();
        try {
            connection = JDBCUtils.getConnection();

            statement = connection.createStatement();

            String sql = "select * from student";

            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                Integer sid = resultSet.getInt("sid");
                String name = resultSet.getString("name");
                Integer age = resultSet.getInt("age");
                Date birthday = resultSet.getDate("birthday");

                Student student = new Student(sid, name, age, birthday);

                list.add(student);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, statement, resultSet);
        }
        return list;
    }

    @Override
    public Student findById(Integer id) {
        Student student = new Student();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();
            String sql = "select * from student where sid='" + id + "'";

            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                Integer sid = resultSet.getInt("sid");
                String name = resultSet.getString("name");
                Integer age = resultSet.getInt("age");
                Date birthday = resultSet.getDate("birthday");

                student.setSid(sid);
                student.setName(name);
                student.setAge(age);
                student.setBirthday(birthday);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, statement, resultSet);
        }
        return student;
    }

    @Override
    public int insert(Student stu) {
        Connection connection = null;
        Statement statement = null;
        int result = 0;

        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();

            java.util.Date birthday = stu.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(birthday);
            String sql = " insert into student values ('" + stu.getSid() + "','" + stu.getName() + "','" + stu.getAge() + "','" + format + "')";

            result = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, statement);
        }
        return result;
    }

    @Override
    public int update(Student stu) {
        Connection connection = null;
        Statement statement = null;
        int result = 0;

        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();

            java.util.Date birthday = stu.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(birthday);
            String sql = " update student set sid = '" + stu.getSid() + "' , name = '" + stu.getName() + "', age = '" + stu.getAge() + "' , birthday = '" + birthday + "' where sid = '" + stu.getSid() + "'";

            result = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, statement);
        }
        return result;
    }

    @Override
    public int delete(Integer id) {
        Connection connection = null;
        Statement statement = null;
        int result = 0;

        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();

            String sql = "delete from student where sid='" + id + "' ";

            result = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, statement);
        }
        return result;
    }
}

JDBCDruid连接池配置

properties 复制代码
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.188.140:3306/db14
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

JdbcDruidUtil

java 复制代码
import com.alibaba.druid.pool.DruidDataSourceFactory;

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

/**
 * 基于Druid连接池获取数据库连接工具类
 */
public class JdbcDruidUtil {
     //数据库连接池对象
     private static DataSource dataSource;
     static{
         try {
             //获取读取配置文件的字节输入流对象
             InputStream is = JdbcDruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
             //创建Properties对象
             Properties pop = new Properties();
             //加载配置文件
             pop.load(is);
             //创建连接池对象
             dataSource = DruidDataSourceFactory.createDataSource(pop);
         }catch(Exception e){
             e.printStackTrace();
         }
     }
    //获取数据库连接对象
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }
    //关闭连接对象
    public static void closeConnection(Connection connection){
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //提交事务
    public static void commit(Connection connection){
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //事务回滚
    public static void rollback(Connection connection){
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭Statement对象
    public static void closeStatement(Statement statement){
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭ResultSet
    public static void closeResultSet(ResultSet resultSet) {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //DML操作时关闭资源
    public static void closeResource(Statement statement,Connection connection){
        //先关闭Statement对象
        closeStatement(statement);
        //在关闭Connection对象
        closeConnection(connection);
    }
    //查询时关闭资源
    public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
        //先关闭ResultSet
        closeResultSet(resultSet);
        //在闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
    }
}

JdbcUtils

java 复制代码
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Jdbc工具类
 */
public class JdbcUtils {
    private static String url;
    private static String name;
    private static String pwd;

    static {
        try{
            //实例化Properties对象
            Properties prop = new Properties();
            //获取读取properties文件的字节输入流对象
            InputStream is = JdbcTest2.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //读取properties文件并解析
            prop.load(is);
            //获取连接数据库的url
            url = prop.getProperty("url");
            //获取连接数据库的用户名
            name = prop.getProperty("username");
            //获取连接数据库的密码
            pwd = prop.getProperty("pwd");
            //获取数据库驱动全名
            String drivername = prop.getProperty("driver");
            //加载并注册驱动
            Class.forName(drivername);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //获取数据库连接对象
    public static Connection getConnection(){
        Connection connection = null;
        try {
           connection = DriverManager.getConnection(url,name,pwd);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }
    //关闭连接对象
    public static void closeConnection(Connection connection){
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //提交事务
    public static void commit(Connection connection){
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //事务回滚
    public static void rollback(Connection connection){
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭Statement对象
    public static void closeStatement(Statement statement){
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭ResultSet
    public static void closeResultSet(ResultSet resultSet) {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //DML操作时关闭资源
    public static void closeResource(Statement statement,Connection connection){
        //先关闭Statement对象
        closeStatement(statement);
        //在关闭Connection对象
        closeConnection(connection);
    }
    //查询时关闭资源
    public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
        //先关闭ResultSet
        closeResultSet(resultSet);
        //在闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
    }
}

自定义连接池

java 复制代码
package com.fengfeng;

import com.fengfeng.utils.JDBCUtils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/**
 * @Author: fengfeng
 * @Date: 2022/07/24/13:57
 * @Description: 业余爱好者
 */
public class MyDtaSource implements DataSource {
    // 准备容器,用于保存多个连接对象
    private static List<Connection> connections = Collections.synchronizedList(new ArrayList<>());
    
    //定义静态代码块,通过工具列获取10个连接对象
    static {
        for (int i = 0; i <= 10; i++) {
            Connection connection = JDBCUtils.getConnection();
            connections.add(connection);
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (connections.size() > 0){
            Connection remove = connections.remove(0);
            return remove;
        }else {
            throw new RuntimeException("连接数量用尽");
        }
    }

    public int getSize(){
        return connections.size();
    }
    
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
相关推荐
我要学编程(ಥ_ಥ)1 小时前
滑动窗口算法专题(1)
java·数据结构·算法·leetcode
niceffking1 小时前
JVM 一个对象是否已经死亡?
java·jvm·算法
真的很上进1 小时前
【Git必看系列】—— Git巨好用的神器之git stash篇
java·前端·javascript·数据结构·git·react.js
科研小白_d.s2 小时前
intellij-idea创建html项目
java·html·intellij-idea
XXXJessie2 小时前
c++249多态
java·c++·servlet
喝旺仔la2 小时前
VSCode的使用
java·开发语言·javascript
骆晨学长2 小时前
基于Springboot的助学金管理系统设计与实现
java·spring boot·后端
尘浮生2 小时前
Java项目实战II基于Java+Spring Boot+MySQL的大型商场应急预案管理系统(源码+数据库+文档)
java·开发语言·数据库·spring boot·spring·maven·intellij-idea
dawn1912282 小时前
SpringMVC 中的域对象共享数据
java·前端·servlet
Xwzzz_2 小时前
Nginx配置负载均衡
java·nginx·负载均衡