Press enter to see results or esc to cancel.


Java program to connect to mysql database

This tutorial shows a Simple java program to connect to MySql database and do a basic select operation from the table.

  1. Project Structure in Ecllipse IDE.
  2. This project uses MySql Connector jar. You have to download it and add to class path.
    Download Mysql Connector jar here.
  3. DB_Connection.java
    package com.chillyfacts.com;
    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;
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    	}catch (Exception e) {
    		System.out.println(e);
    	}
    	return connection;
         }
    }
    
  4. If you run the above class as ‘Run as Java Application’. You will get a output as shown which means the connection to MySql is successful. If the out put is null that means connection to Database is not successful.
  5. This DAO.java class is a program to select a data from table and show it in console.
    DAO.java

    package com.chillyfacts.com;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    public class DAO {
        public static void main(String[] args) {
    	DAO obj_DAO=new DAO();
    	obj_DAO.Check_Data();
        }
        public void Check_Data(){
    	DB_Connection obj_DB_Connection=new DB_Connection();
    	Connection connection=obj_DB_Connection.get_connection();
    	PreparedStatement ps=null;
    	try {
    	    String query="select * from categories";
    	    ps=connection.prepareStatement(query);
    	    ResultSet rs=ps.executeQuery();
    	    while(rs.next()){
    	        System.out.println("Catagory- "+rs.getString("category_name"));
    	    }
    	} catch (Exception e) {
    	    System.out.println(e);
    	}
        }
    }
    
  6. If you run the DAO.java class as Run as Java Application, You will get the below output.
  7. Download the project Here.
    Download ConnectMysql.rar

Comments

Leave a Comment