zoukankan      html  css  js  c++  java
  • JDBC连接数据库的通用方法

    package jdbc;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;
    
    public class JDBCUtil {
    
        public Connection getConnection(){
            Connection connection = null;
            try {
                Properties properties = new Properties();
                InputStream in = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
                properties.load(in);
                
                String user = properties.getProperty("user");
                String password = properties.getProperty("password");
                String jdbcUrl = properties.getProperty("jdbcUrl");
                String driver = properties.getProperty("driver");
                
                //加载驱动
                Class.forName(driver);
                
                //返回连接
                connection =  DriverManager.getConnection(jdbcUrl, user, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                if(connection != null){
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            return connection;
            
        }
        
        public static void main(String[] args) {
            Connection connection = new JDBCUtil().getConnection();
            System.out.println(connection.toString());
        }
    }
  • 相关阅读:
    《代码阅读方法与实践》阅读笔记之二
    《代码阅读方法与实践》阅读笔记一
    专业实训题目需求分析
    阅读计划
    第二阶段Sprint10
    第二阶段Sprint9
    第二阶段Sprint8
    第二阶段Sprint7
    第二阶段个人工作总结(8)
    第二阶段个人工作总结(7)
  • 原文地址:https://www.cnblogs.com/noaman/p/6647111.html
Copyright © 2011-2022 走看看