Press enter to see results or esc to cancel.


How to connect to remote MySql database from NetBeans

This tutorial shows java program to connect to remote MySql Database from NetBeans IDE.

  1. Include the MySql jar in classpath of the project. You can download MySql jar here.
  2. Update your Database information in the program.
    DB_Connection.java

    package DB_Connection;
    import java.sql.Connection;
    import java.sql.DriverManager;
    public class DB_Connection {
         public static void main(String[] args) {
    	DB_Connection obj_DB_Connection=new DB_Connection();
    	Connection connection=null;
    	connection=obj_DB_Connection.get_connection();
    	System.out.println(connection);
         }
         public Connection get_connection(){
    	Connection connection=null;
    Class.forName("com.mysql.jdbc.Driver");
    connection=DriverManager.getConnection("jdbc:mysql://hostname:3306/databasename","username","password");
    	}catch (Exception e) {
    		System.out.println(e);
    	}
    	return connection;
         }
    }
    

    for localhost connection you can use the db information as,

    connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username","password");	
    
  3. The below class will will do a simple select operations from the table.
    JavaApplication1.java

    package javaapplication1;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    public class JavaApplication1 {
        public static void main(String[] args) {
    	JavaApplication1 obj_DAO=new JavaApplication1();
    	obj_DAO.Check_Data();
        }
        public void Check_Data(){
    	DB_Connection.DB_Connection obj_DB_Connection=new DB_Connection.DB_Connection();
    	Connection connection=obj_DB_Connection.get_connection();
    	PreparedStatement ps=null;
    	try {
    	    String query="select * from jinu";
    	    ps=connection.prepareStatement(query);
    	    ResultSet rs=ps.executeQuery();
    	    while(rs.next()){
    	        System.out.println("name- "+rs.getString("name"));
    	    }
    	} catch (Exception e) {
    	    System.out.println(e);
    	}
        }
    }