Web Applications Development

Thursday, July 3, 2025

Export and Import Data from MongoDB

Export Data from MongoDB

To export data from a MongoDB database using MongoDB Tools, particularly mongodump and mongoexport, follow the appropriate method based on your use case:

✅ Option 1: Use mongoexport

Exports collection data in JSON or CSV format.

🔹 Example: Export a collection to JSON

mongoexport --uri="mongodb://localhost:27017" \

  --db=mydatabase \

  --collection=mycollection \

  --out=mycollection.json

🔹 Example: Export to CSV (with selected fields)

mongoexport --uri="mongodb://localhost:27017" \

  --db=mydatabase \

  --collection=mycollection \

  --type=csv \

  --fields=name,age,email \

  --out=mycollection.csv

✅ Option 2: Use mongodump

Creates a binary backup of the database or collection (good for restoring later using mongorestore).

🔹 Example: Dump entire database

mongodump --uri="mongodb://localhost:27017" \

  --db=mydatabase \

  --out=./dump/

🔹 Example: Dump a single collection

mongodump --uri="mongodb://localhost:27017" \

  --db=mydatabase \

  --collection=mycollection \

  --out=./dump/

🔄 To Restore Data Later:

🔹 Using mongorestore for a full dump

mongorestore --uri="mongodb://localhost:27017" ./dump/

📦 Install MongoDB Tools

If you don't have the tools installed:

On Ubuntu: sudo apt-get install mongodb-database-tools

On macOS:

brew tap mongodb/brew

brew install mongodb-database-tools

Or download directly:

https://www.mongodb.com/try/download/database-tools 

Saturday, April 13, 2024

Java Database Connectivity

  • JDBC provides a standard library for accessing relational databases.
  • JDBC API standardizes, the approach for connecting to databases, the syntax for sending SQL queries and committing transactions and provides the data structure representing the result.
  • By using JDBC you can change database hosts, ports, and even database vendors with minimal changes to your code.

 7 basic steps in using JDBC

  1. Load the JDBC driver
  2. Define the connection URL
  3. Establish the connection
  4. Create a Statement object
  5. Execute a query or update
  6. Process the results
  7. Close the connection
Note : Please note that below steps were demonstrated with MySQL Database.
  1. Load the JDBC driver
    • The driver is the software that knows the way to communicate with database server
    • To load the driver, load the appropriate class; a static block in the driver class itself automatically makes a driver instance and registers it with the JDBC driver manager
    • Class.forName method takes a string representing a fully qualified class name and loads the corresponding class.
public class SQLConnection {
   
    public void mySQLConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

2. Define the connection URL

  • Specify the location of the database server
  • URLs referring to databases use the jdbc: protocol and embed the server host, port, and database name
  • The exact format is defined in the documentation that comes with the particular driver
public class SQLConnection {
    public void mySQLConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
                           // "jdbc:mysql//" + host +":" + port + “/" + dbName;
            String mySqlURL = "jdbc:mysql://localhost:3306/cgj";
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

3. Establish the connection

  • To make the connection with the database, pass the URL, database username, and database password to the getConnection method of the DriverManager class
        
import java.sql.*;

public class SQLConnection {
    public void mySQLConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
                           // "jdbc:mysql//" + host +":" + port + “/" + dbName;
            String mySqlURL = "jdbc:mysql://localhost:3306/cgj";
            Connection con=DriverManager.getConnection(mySqlURL,"root","root");  
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

4. Create a Statement object

  • Used to send queries and commands to the database.
  • Most of the database drivers permit multiple concurrent Statement objects to be open on the same connection
import java.sql.*;

public class SQLConnection {
    public void mySQLConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
                           // "jdbc:mysql//" + host +":" + port + “/" + dbName;
            String mySqlURL = "jdbc:mysql://localhost:3306/cgj";
            Connection con=DriverManager.getConnection(mySqlURL,"root","root");
            Statement stmt=con.createStatement();
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

5. Execute a query or update
  • You can use Statement object to send SQL queries by using the executeQuery method, which returns an object of type ResultSet
  • executeUpdate method is used for UPDATE, INSERT, or DELETE commands, which will return the number of rows affected, which could be zero
import java.sql.*;

public class SQLConnection {
    public void mySQLConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
                           // "jdbc:mysql//" + host +":" + port + “/" + dbName;
            String mySqlURL = "jdbc:mysql://localhost:3306/cgj";
            Connection con=DriverManager.getConnection(mySqlURL,"root","root");
            Statement stmt=con.createStatement();

            String query = "select * from employee";
            ResultSet resultSet = stmt.executeQuery(query);
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

6. Process the results

  • Use the next method of ResultSet to move through the table a row at a time
  • Within a row, ResultSet provides various getXxx methods that take a column name or column index as an argument and return the result in a variety of different Java types
  • The first column in a ResultSet row has index 1, not 0
import java.sql.*;

public class SQLConnection {
    public void mySQLConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
                           // "jdbc:mysql//" + host +":" + port + “/" + dbName;
            String mySqlURL = "jdbc:mysql://localhost:3306/cgj";
            Connection con=DriverManager.getConnection(mySqlURL,"root","root");
            Statement stmt=con.createStatement();

            String query = "select * from employee";
            ResultSet resultSet = stmt.executeQuery(query);

            while(rs.next())  
                System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
 
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

7. Close the connection

  • Closing the connection also closes the corresponding Statement and ResultSet objects
  • Postpone closing the connection if there's to perform additional database operations
  • Reusing existing connections is such an important optimization that the JDBC 2.0 API defines a ConnectionPoolDataSource interface for obtaining pooled connections

import java.sql.*;

public class SQLConnection {
    public void mySQLConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
                           // "jdbc:mysql//" + host +":" + port + “/" + dbName;
            String mySqlURL = "jdbc:mysql://localhost:3306/cgj";
            Connection con=DriverManager.getConnection(mySqlURL,"root","root");
            Statement stmt=con.createStatement();

            String query = "select * from employee";
            ResultSet resultSet = stmt.executeQuery(query);

            while(rs.next())  
                System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));

            con.close();
 
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
    }
}

Saturday, April 6, 2024

Servlet

 Handling the Client Request: Form Data

  • From data can be attached to the end of the URL for GET requests
    • Read the URL
    • Separate pairs at the ampersands, then separate the parameter names from the parameter values
  • Form data can also be sent to the server on a separate line for POST request.


Introduction to J2EE

 

 Web Application Model


Servlet

Servlets are Java programs that run on Web or application servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server


Tasks Performed
  • Read the explicit data sent by the client
  • Read the implicit HTTP request data sent by the browser
  • Generate the results
  • Send the explicit data (i.e., the document) to the client.
  • Send the implicit HTTP response data
Advantages of Servlets
  • Efficient
    • If there are many requests to the same servlet, only a single copy of the servlet class would be loaded
  • Convenient
    • Have utilities like parsing, decoding HTML form data, cookie & session handling, etc.
  • Powerful
    • Servlets can communicate directly to the Web server
    • Multiple servlets can also share data
  • Portable
    • Run on All operating systems and servers
  • Inexpensive
  • Secure
    • Servlets are not executed by general-purpose operating system shells
    • No buffer overflow attacks
What is a container? (Servlet Engine)

Servlets don’t have a main method. Because of that, they are under the control of another java application called container : Tomcat is an example of a container

Servlet Life Cycle



  • init
    • Executed once when the servlet is first loaded or at server start.
    • Performs initializations such as setting up a database connection, loading a data file, etc.
  • service
    • Each time the server receives a request for a servlet, the server spawns a new thread and calls service(). 
    • The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as appropriate.
  • destroy
    • Called when server deletes servlet instance.
    • It will close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities

Basic Servlet Structure



Web Application Structure






Next Chapter : Servlet



Popular Posts