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());
        }
    }
  • 相关阅读:
    (转)详谈高端内存和低端内存
    高级声明------定义一个函数指针数组指针
    A Bug's Life POJ
    How Many Answers Are Wrong HDU
    A
    B
    数据处理----离散化
    Serval and Parenthesis Sequence CodeForces
    D
    C
  • 原文地址:https://www.cnblogs.com/noaman/p/6647111.html
Copyright © 2011-2022 走看看