JDBC应用实例

首先要创建一个properties文件在src目录下。这个文件是用来存储自定义变量的,这里用于存储JDBC连接的变量的。

 再创建一个工具类,用于连接数据库。

public class JDBCUtil {
    static Properties properties = new Properties();
    //加载驱动
    static {
        InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(resourceAsStream);
            Class.forName(properties.getProperty("driverClass"));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接对象
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username"),properties.getProperty("password"));
    }



    public static void close(ResultSet rs, Connection con, PreparedStatement ps){
        try {
            if (rs!=null){
                rs.close();
            }
            if (con!=null){
                con.close();
            }
            if (ps!=null){
                ps.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

 上一篇文章里已经说过了jar的导入了,这里就不讲了。到这里就完成了数据库的连接了。

可以编写功能了。

先建好实体类。

再创建Dao层

 

AdminDao是一个接口, AdminDaoImpl实现它的方法。sql语句就是写在AdminDaoImpl里的。

 

 

由于增删查改是大多数实体类都会用到的,所以使用了一个BaseDao来定义,这样就不用每个方法都写一次了。

package Dao;

import java.util.List;

public interface BaseDao<T> {
    public int insert(T t);
    public int deleteById(Object o );
    public int update(T t);
    public T getById(Object o );
    public List<T> getAll();
}

Dao层后面还有Servies层,Controller层,不过我嫌麻烦就没写了。这就是常说的三层架构。其实现在写的东西就是mybatis这种框架的底层代码,以后我们写代码都是用写好的框架的,上面这些东西自己敲大概要半小时,但是用了框架都不用几分钟就自动生成了。mybatisplus会自动生成Servies层之前的所有类,数据库映射文件也会生成,你只需要写sql语句就行了,很方便简洁。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值