jdbc工具类

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

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(自己写的)

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
/**
 * @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();
            }
        }
    }
}

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

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连接池配置

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

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

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);
    }
}

自定义连接池

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;
    }
}

你可能感兴趣的:(Java,java,intellij-idea)