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());
        }
    }
  • 相关阅读:
    struts 提交问题
    struts spring整合出错
    hibernate.cfg.xml
    myeclipse copy问题
    myeclipse copy时出的问题
    mysql sql 语句
    Spring_Hibernate
    WebView
    Notification
    Handler(消息机制)
  • 原文地址:https://www.cnblogs.com/noaman/p/6647111.html
Copyright © 2011-2022 走看看