JDBC中使用Properties类及配置文件的操作

一、properties配置文件

开发中获得连接的4个参数(驱动、URL、用户名、密码)通常都存在配置文件中,方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可。

通常情况下,我们习惯使用properties文件,Java中有专门用来装载配置文件的类Properties(Java.util.Properties),配置文件用来保存一些在程序中可能修改的值,修改时只要修改配置文件即可,而不用修改程序本身。Java配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式。在properties的文件中,在行首加上 # 就是注释这行,或者是用 包括这行也是注释。

#例如
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydatabase
username=root
password=7894561230

二、加载配置文件

public class DBMySQL {
    private static Properties properties = null;
    private Connection connection = null;

    static{ //静态初始化器
        properties = new Properties();
        ClassLoader classLoader = DBMySQL.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("jdbc.properties");

        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //1.定义方法:获取数据库的连接对象
    public Connection getMysqlConnection(){
        String driver = properties.getProperty("mysql.driver").trim();
        String url = properties.getProperty("mysql.url").trim();
        String user = properties.getProperty("mysql.user").trim();
        String password = properties.getProperty("mysql.password").trim();

        //1.加载驱动
        try {
            Class.forName(driver);
            //2.连接数据库,获取连接对象
            if(connection == null){
                connection = DriverManager.getConnection(url,user,password);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }

    //2.定义方法:用于关闭数据库的连接对象
    public void releaseConnection(){
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
  • 通过IO读取文件
  • 创建Properties对象
  • 使用Properties对象的load(流)方法加载数据
  • 使用Properties对象的getProperty(键)方法获取对应值

三、用JDBC建立连接

由于本文主要介绍.properties配置文件的使用,固此处不做赘述

public class StudentDaoimpl implements IStundentDao {
    private Connection connection = null;//连接对象
    private PreparedStatement ps  =  null;//语句对象
    private ResultSet rs = null;//结果集对象
    @Override
    public boolean insert(Student s) {
        DBMySQL dbms = new DBMySQL();
        connection = dbms.getMysqlConnection();

        //创建Student对象
        String insert_sql = "insert into student values(?,?,?,?)";

        int rows = 0;
        try {
            ps = connection.prepareStatement(insert_sql);
            ps.setString(1,s.getSid());
            ps.setString(2,s.getSname());
            ps.setInt(3,s.getSage());
            ps.setString(4, s.getSex());

            rows = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rows > 0;
    }

    @Override
    public boolean delete(String id) {
        DBMySQL dbm = new DBMySQL();
        connection = dbm.getMysqlConnection();
        String delete_sql = "delete from student where sid=?";
        int rows = 0;
        try {
            ps = connection.prepareStatement(delete_sql);
            ps.setString(1,id);
            rows = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows > 0;
    }

    @Override
    public boolean update(Student s) {
        DBMySQL dbm = new DBMySQL();
        connection = dbm.getMysqlConnection();
        String update_sql = "update student set sid=?,age=?,sex=? where sname=?";
        int rows = 0;
        try {
            ps = connection.prepareStatement(update_sql);

            ps.setString(1,s.getSid());
            ps.setInt(2,s.getSage());
            ps.setString(3,s.getSex());
            ps.setString(4,s.getSname());

            rows = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows > 0;
    }

    @Override
    public List<Student> findAll() {

        List<Student> studentList = new ArrayList<>();
        DBMySQL dbms = new DBMySQL();
        String query_sql = "select * from student";
        connection = dbms.getMysqlConnection();//获取数据库的连接对象
        try {
            //防止注入式攻击:将来在执行sql语句的过程中,sql语句已经被编译成二进制代码,即便黑客水平很高,二进制编码截取了但无法知道将来传递什么样的参数
            ps = connection.prepareStatement(query_sql);//获取语句对象,同时对sql语言进行预编译
            rs = ps.executeQuery();

            //遍历结果集,将结果集中每行数据封装到一个Student对象
            while(rs.next()){
                Student s = new Student();
                s.setSid(rs.getString("sid"));
                s.setSname(rs.getString("sname"));
                s.setSage(rs.getInt("age"));
                s.setSex(rs.getString("sex"));

                studentList.add(s);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return studentList;
    }

四、Properties对象的常用方法

1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

6.keySet(),获取键集合(Properties继承Hashtable,内部通过Map实现)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值