获取mysql数据库数据的流程及JDBCUtils工具类

获取mysql数据库数据的流程:

注册驱动(DriverManager)—>获取连接(Connection)—>获取对数据库操作的预处理对象(PrepareStatement)—>执行sql语句并返回到数据集中(ResultSet)—>释放资源(close);

由于经常要使用连接数据库都需要进行注册连接等,每次都重复写很麻烦,所以将我们用JDBCUtils即JDBC工具类来替代;

JDBCUtils工具类

public class JDBCUtils {
//驱动名
    public static final String driver = "com.mysql.jdbc.Driver";
//地址
    public static final String url = "jdbc:mysql://localhost:3306/testdb";
//用户名
    public static final String username = "root";
//密码
    public static final String passwd = "root";
//    注册驱动
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
//    获取连接;
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,username,passwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
//    关闭释放资源
    public static void close(ResultSet resultSet, Statement statement,Connection connection){
            if (resultSet!=null){
                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();
                }
            }
    }
}

测试类

public class JDBCUtilsTest {
    public static void main(String[] args) {
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        Connection connection = null;
        String sql = "select * from employee";
        try {
            connection = JDBCUtils.getConnection();//获取连接
            preparedStatement = connection.prepareStatement(sql);//获取对数据库操作的预处理对象
            resultSet = preparedStatement.executeQuery();//执行sql语句并返回到数据集中
            while (resultSet.next()){
            System.out.println(resultSet.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
        //关闭连接,释放资源
            JDBCUtils.close(resultSet,preparedStatement,connection);
        }



    }
}

猜你喜欢

转载自blog.csdn.net/python_small_pan/article/details/96429022