使用IO流,操作Jdbc连接MySql数据库

1.写连接MySql数据配置文件:
文件名称:dbconfig.properties

DRIVER = com.mysql.jdbc.Driver
URL = jdbc:mysql://localhost:3306/javadb
USER = root
PASSWORD = root

2.使用IO流形式加载:

    static{
        InputStream in = DataBase.class.getClassLoader().getResourceAsStream("dbconfig.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            Class.forName((String) p.get("DRIVER"));
            URL = (String) p.get("URL");
            USER = (String) p.get("USER");
            PASSWORD = (String) p.get("PASSWORD");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

-连接:

    public static Connection getConn() throws SQLException {
        Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
        return connection;
    }

-关闭:

    public static void close(Connection conn, Statement st, ResultSet re){
        try {
            if(conn!=null){
                conn.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(st!=null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(re!=null) {
                        re.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
发布了29 篇原创文章 · 获赞 1 · 访问量 4394

猜你喜欢

转载自blog.csdn.net/qq_39288961/article/details/98750249