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);
    
    • 输出结果

    完美^_^

  • 相关阅读:
    phpstorm常用快捷键
    tp3.2.3运用phpexcel将excel文件导入mysql数据库
    TP3.2加载外部PHPexcel类,实现导入和导出
    Navicat常用快捷键
    thnkphp框架面试问题
    PHPSQL注入
    PHP4个载入语句的区别
    goflyway简单使用
    ubuntu16.04 HyperLedger Fabric 1.2.0 开发环境搭建
    DApp demo之pet-shop
  • 原文地址:https://www.cnblogs.com/kongieg/p/10062354.html
Copyright © 2011-2022 走看看