zoukankan      html  css  js  c++  java
  • 使用Properties配置数据库驱动

    优点:

    1.   便于修改连接属性。只需在配置文件中修改,不需要在代码中修改了。
    2.        更易于维护代码安全性。

    方法:

    • 在src文件嘉下创建database.properties文本文件;添加内容:

      

    driver = com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/y1
    name=root
    password=root
    
    • 创建工具类MyJDBCUtiles.java,添加代码:  
    package com.kong.JDBCUtils;
    
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    public class MyJDBCUtiles {
        private MyJDBCUtiles(){}
        private static Connection con;
        private static String driver;
        private static String url;
        private static String name;
        private static String password;
        static{
            try {
                InputStream is = MyJDBCUtiles.class.getClassLoader().getResourceAsStream("database.properties");
                Properties properties = new Properties();
                properties.load(is);
                driver = properties.getProperty("driver");
                url = properties.getProperty("url");
                name = properties.getProperty("name");
                password = properties.getProperty("password");
                Class.forName(driver);
                con = DriverManager.getConnection(url, name, password);
            }catch (Exception ep){
                throw new RuntimeException(ep+"数据库连接失败");
            }
        }
        public static Connection getConnection(){
            return con;
        }
    
    • 其他类使用时调用即可
            Connection con = MyJDBCUtiles.getConnection();
            System.out.println(con);
    
    • 输出结果

    完美^_^

  • 相关阅读:
    IDEA中项目编码格式设置
    font awesome 页面小图标
    ffmpeg无损MP4转TS 及bat批量脚本
    Mysql超百万数据的导入导出
    查询流水表中所有用户最后一条和第一条记录
    css样式实现网页全黑白
    jsp中二维码展示及异步轮询查询
    支付宝当面付对接
    微信native支付对接
    Java和python实现斐波那契数列的感触
  • 原文地址:https://www.cnblogs.com/kongieg/p/10062354.html
Copyright © 2011-2022 走看看