Here’s a sample code snippet that demonstrates how to write data to a MongoDB database using Java and the MongoDB Java Driver: import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoDBDataWriter { public static void main(String[] args) { // MongoDB connection URI String uri = "mongodb://localhost:27017"; // Database and collection names String databaseName = "mydatabase"; String collectionName = "customers"; try { // Connect to MongoDB MongoClientURI mongoURI = new MongoClientURI(uri); MongoClient mongoClient = new MongoClient(mongoURI); // Access the database MongoDatabase database = mongoClient.getDatabase(databaseName); // Access the collection MongoCollection<Document> collection = database.getCollection(collectionName); // Create a new document Document document = new Document(); document.append("name", "John Doe"); document.append("email", "[email protected]"); // Insert the document into the collection collection.insertOne(document); System.out.println("Data inserted successfully!"); // Close the MongoDB client mongoClient.close(); } catch (Exception e) { e.printStackTrace(); } } } Make sure you have the MongoDB Java Driver (such as mongodb-driver.jar) included in your classpath. If not, you can download it from the official MongoDB website or include it as a Maven/Gradle dependency. The code connects to the MongoDB database using the provided connection URI, accesses the specified database and collection, creates a new Document object representing the data to be inserted, and inserts it into the collection using the insertOne() method. In this example, the document contains name and email fields. Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources. Make sure you have the MongoDB Java Driver (such as mongodb-driver.jar) included in your classpath. If not, you can download it from the official MongoDB website or include it as a Maven/Gradle dependency. The code connects to the MongoDB database using the provided connection URI, accesses the specified database and collection, creates a new Document object representing the data to be inserted, and inserts it into the collection using the insertOne() method. In this example, the document contains name and email fields. Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.
Read data in MongoDB using Java
Here’s a sample code snippet that demonstrates how to read data from a MongoDB database using Java and the MongoDB Java Driver: import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoDBDataReader { public static void main(String[] args) { // MongoDB connection URI String uri = "mongodb://localhost:27017"; // Database and collection names String databaseName = "mydatabase"; String collectionName = "customers"; try { // Connect to MongoDB MongoClientURI mongoURI = new MongoClientURI(uri); MongoClient mongoClient = new MongoClient(mongoURI); // Access the database MongoDatabase database = mongoClient.getDatabase(databaseName); // Access the collection MongoCollection<Document> collection = database.getCollection(collectionName); // Perform a find operation FindIterable<Document> documents = collection.find(); // Iterate over the documents for (Document document : documents) { String id = document.getObjectId("_id").toString(); String name = document.getString("name"); String email = document.getString("email"); System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("————————–"); } // Close the MongoDB client mongoClient.close(); } catch (Exception e) { e.printStackTrace(); } } } Make sure you have the MongoDB Java Driver (such as mongodb-driver.jar) included in your classpath. If not, you can download it from the official MongoDB website or include it as a Maven/Gradle dependency. The code connects to the MongoDB database using the provided connection URI, accesses the specified database and collection, and performs a find operation using the find() method on the collection. It then iterates over the resulting documents and retrieves the values of the desired fields. In this example, it assumes each document has _id, name, and email fields. Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.
Delete data in PostgreSQL using Java
Here’s a sample code snippet that demonstrates how to delete data from a PostgreSQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class PostgreSQLDataDeleter { public static void main(String[] args) { // Database credentials String url = "jdbc:postgresql://localhost:5432/mydatabase"; String username = "postgres"; String password = "password"; // SQL query String query = "DELETE FROM customers WHERE id = ?"; try { // Register JDBC driver Class.forName("org.postgresql.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter value pstmt.setInt(1, 1); // Assuming ID 1 needs to be deleted // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the deletion was successful if (rowsAffected > 0) { System.out.println("Data deleted successfully!"); } else { System.out.println("Failed to delete data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual PostgreSQL database connection details. Additionally, modify the query variable to match your desired SQL DELETE statement. This code snippet assumes you have the PostgreSQL JDBC driver (e.g., postgresql.jar) included in your classpath. If not, you can download it from the official PostgreSQL website or include it as a Maven/Gradle dependency. The code connects to the PostgreSQL database, prepares a DELETE statement with a placeholder, sets the parameter value using the appropriate setter method (setInt, setString, etc.), and executes the query using executeUpdate. It then checks the number of affected rows to determine if the deletion was successful. Finally, it closes the resources to free up memory. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Write data to PostgreSQL using Java
Here’s a sample code snippet that demonstrates how to write data to a PostgreSQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class PostgreSQLDataWriter { public static void main(String[] args) { // Database credentials String url = "jdbc:postgresql://localhost:5432/mydatabase"; String username = "postgres"; String password = "password"; // SQL query String query = "INSERT INTO customers (name, email) VALUES (?, ?)"; try { // Register JDBC driver Class.forName("org.postgresql.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter values pstmt.setString(1, "John Doe"); pstmt.setString(2, "[email protected]"); // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the insertion was successful if (rowsAffected > 0) { System.out.println("Data inserted successfully!"); } else { System.out.println("Failed to insert data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual PostgreSQL database connection details. Additionally, modify the query variable to match your desired SQL INSERT statement. This code snippet assumes you have the PostgreSQL JDBC driver (e.g., postgresql.jar) included in your classpath. If not, you can download it from the official PostgreSQL website or include it as a Maven/Gradle dependency. The code connects to the PostgreSQL database, prepares an INSERT statement with placeholders, sets the parameter values using the setString, setInt, or other setter methods, and executes the query using executeUpdate. It then checks the number of affected rows to determine if the insertion was successful. Finally, it closes the resources to free up memory. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Read data from PostgreSQL using Java
Here’s a sample code snippet that demonstrates how to read data from a PostgreSQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PostgreSQLDataReader { public static void main(String[] args) { // Database credentials String url = "jdbc:postgresql://localhost:5432/mydatabase"; String username = "postgres"; String password = "password"; // SQL query String query = "SELECT * FROM customers"; try { // Register JDBC driver Class.forName("org.postgresql.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery(query); // Process the result set while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("————————–"); } // Close the resources rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual PostgreSQL database connection details. Additionally, modify the query variable to match your desired SQL query. This code snippet assumes you have the PostgreSQL JDBC driver (e.g., postgresql.jar) included in your classpath. If not, you can download it from the official PostgreSQL website or include it as a Maven/Gradle dependency. The code connects to the PostgreSQL database, executes the SQL query, and iterates over the result set to retrieve the data. In this example, it assumes a table named “customers” with columns “id,” “name,” and “email.” Adjust the column names as per your table schema. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Delete data in SQL DB using Java
Here’s a sample code snippet that demonstrates how to delete data from a SQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class SQLDataDeleter { public static void main(String[] args) { // Database credentials String url = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase"; String username = "sa"; String password = "password"; // SQL query String query = "DELETE FROM customers WHERE id = ?"; try { // Register JDBC driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter value pstmt.setInt(1, 1); // Assuming ID 1 needs to be deleted // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the deletion was successful if (rowsAffected > 0) { System.out.println("Data deleted successfully!"); } else { System.out.println("Failed to delete data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual SQL database connection details. Additionally, modify the query variable to match your desired SQL DELETE statement. This code snippet assumes you have the appropriate JDBC driver for your SQL database (e.g., mssql-jdbc.jar for Microsoft SQL Server) included in your classpath. If not, you can download the driver from the respective database vendor’s website or include it as a Maven/Gradle dependency. The code connects to the SQL database, prepares a DELETE statement with a placeholder, sets the parameter value using the appropriate setter method (setInt, setString, etc.), and executes the query using executeUpdate. It then checks the number of affected rows to determine if the deletion was successful. Finally, it closes the resources to free up memory. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Update data from SQL DB using Java
Here’s a sample code snippet that demonstrates how to update data in a SQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class SQLDataUpdater { public static void main(String[] args) { // Database credentials String url = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase"; String username = "sa"; String password = "password"; // SQL query String query = "UPDATE customers SET email = ? WHERE id = ?"; try { // Register JDBC driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter values pstmt.setString(1, "[email protected]"); pstmt.setInt(2, 1); // Assuming ID 1 needs to be updated // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the update was successful if (rowsAffected > 0) { System.out.println("Data updated successfully!"); } else { System.out.println("Failed to update data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual SQL database connection details. Additionally, modify the query variable to match your desired SQL UPDATE statement. This code snippet assumes you have the appropriate JDBC driver for your SQL database (e.g., mssql-jdbc.jar for Microsoft SQL Server) included in your classpath. If not, you can download the driver from the respective database vendor’s website or include it as a Maven/Gradle dependency. The code connects to the SQL database, prepares an UPDATE statement with placeholders, sets the parameter values using the appropriate setter methods (setString, setInt, etc.), and executes the query using executeUpdate. It then checks the number of affected rows to determine if the update was successful. Finally, it closes the resources to free up memory. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Write data to SQL DB using Java
Here’s a sample code snippet that demonstrates how to write data to a SQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class SQLDataWriter { public static void main(String[] args) { // Database credentials String url = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase"; String username = "sa"; String password = "password"; // SQL query String query = "INSERT INTO customers (name, email) VALUES (?, ?)"; try { // Register JDBC driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter values pstmt.setString(1, "John Doe"); pstmt.setString(2, "[email protected]"); // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the insertion was successful if (rowsAffected > 0) { System.out.println("Data inserted successfully!"); } else { System.out.println("Failed to insert data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual SQL database connection details. Additionally, modify the query variable to match your desired SQL INSERT statement. This code snippet assumes you have the appropriate JDBC driver for your SQL database (e.g., mssql-jdbc.jar for Microsoft SQL Server) included in your classpath. If not, you can download the driver from the respective database vendor’s website or include it as a Maven/Gradle dependency. The code connects to the SQL database, prepares an INSERT statement with placeholders, sets the parameter values using the setString, setInt, or other setter methods, and executes the query using executeUpdate. It then checks the number of affected rows to determine if the insertion was successful. Finally, it closes the resources to free up memory. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Read data in SQL DB using Java
Here’s a sample code snippet that demonstrates how to read data from a SQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLDataReader { public static void main(String[] args) { // Database credentials String url = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase"; String username = "sa"; String password = "password"; // SQL query String query = "SELECT * FROM customers"; try { // Register JDBC driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery(query); // Process the result set while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("————————–"); } // Close the resources rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual SQL database connection details. Additionally, modify the query variable to match your desired SQL query. This code snippet assumes you have the appropriate JDBC driver for your SQL database (e.g., mssql-jdbc.jar for Microsoft SQL Server) included in your classpath. If not, you can download the driver from the respective database vendor’s website or include it as a Maven/Gradle dependency. The code connects to the SQL database, executes the SQL query, and iterates over the result set to retrieve the data. In this example, it assumes a table named “customers” with columns “id,” “name,” and “email.” Adjust the column names as per your table schema. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.
Delete data in MySQL using Java
Here’s a sample code snippet that demonstrates how to delete data from a MySQL database using Java and JDBC (Java Database Connectivity): import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class MySQLDataDeleter { public static void main(String[] args) { // Database credentials String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; // SQL query String query = "DELETE FROM customers WHERE id = ?"; try { // Register JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter value pstmt.setInt(1, 1); // Assuming ID 1 needs to be deleted // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the deletion was successful if (rowsAffected > 0) { System.out.println("Data deleted successfully!"); } else { System.out.println("Failed to delete data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } Make sure to replace the url, username, and password variables with your actual MySQL database connection details. Additionally, modify the query variable to match your desired SQL DELETE statement. This code snippet assumes you have the MySQL JDBC driver (e.g., mysql-connector-java.jar) included in your classpath. If not, you can download it from the official MySQL website or include it as a Maven/Gradle dependency. The code connects to the MySQL database, prepares a DELETE statement with a placeholder, sets the parameter value using the appropriate setter method (setInt, setString, etc.), and executes the query using executeUpdate. It then checks the number of affected rows to determine if the deletion was successful. Finally, it closes the resources to free up memory. Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.