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



    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值