Sunday, 22 June 2014

Java Database Connection

        public static String driver="com.mysql.jdbc.Driver";
        public static String url="jdbc:mysql://localhost:3306/dbname;
public static String user="root";
public static String password="root";
    

public static Connection getConnection(){
java.sql.Connection con =null;

try {
Class.forName(driver);
con=DriverManager.getConnection(url, user, password);
if(con!=null){
                                 System.out.println("connection established");
}
else{
System.out.println("connection not established");
}

}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}

        public static void closeConnection(Connection conn){
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

No comments:

Post a Comment