写了个小网站,每次连接数据库都得改端口号,在代码中改有点麻烦,请问怎样将连接数据库的类在配置文件中配置好??
最好有一个典型的列子,谢谢!!

解决方案 »

  1.   

    就是写个配置文件,然后用java来读取配置文件,这样代码网上很多,搜一下
      

  2.   

    可以写个工具类
    public class DBConnection {

    public static Connection getConnection(){

    String url="jdbc:mysql://localhost:3306/gwap";
    String DriverName="com.mysql.jdbc.Driver";
    String username="root";
    String password="mysql";
    Connection conn=null;
    try{
    Class.forName(DriverName);
    System.out.println("********开始进行连接********");
    conn=DriverManager.getConnection(url, username, password);
    System.out.println("********数据库连接成功********");
    }catch(ClassNotFoundException e){
    e.printStackTrace();
    }catch(Exception e1){
    System.out.println("********数据库连接失败********");
    e1.printStackTrace();
    }
    return conn;
    }
    public static void closeConnection(Connection conn){
    if(conn!=null){
    try {
    conn.close();
    } catch (SQLException e) {
    throw new RuntimeException("ERROR.UNEXPECTED");
    }
    }
    }
    public static void closeStatement(Statement stmt){
    if(stmt!=null){
    try {
    stmt.close();
    } catch (SQLException e) {
    throw new RuntimeException("ERROR.UNEXPECTED");
    }
    }
    }
    public static void closePreparedStatement(PreparedStatement pstmt){
    if(pstmt!=null){
    try {
    pstmt.close();
    } catch (SQLException e) {
    throw new RuntimeException("ERROR.UNEXPECTED");
    }
    }
    }
    public static void closeResultSet(ResultSet rs){
    if(rs!=null){
    try {
    rs.close();
    } catch (SQLException e) {
    throw new RuntimeException("ERROR.UNEXPECTED");
    }
    }
    }
    public static void main(String args[]){
    DBConnection.getConnection();
    }
    }
     用hibernate 可以些配置文件