Thursday, June 13, 2024

Node.js path.basename() Method With Examples

Path module in Node.js provides many utility methods to work with file and directory paths. In this article we'll see how to use path.basename() method which returns the last portion of a path that means you can extract the filename from the full path using this method.

Syntax of path.basename()

path.basename(path, suffix)
  • path- This is the file path from which last portion has to be extracted. This is a required parameter.
  • suffix- This is an optional parameter. If the filename ends with the given suffix (extension) then the extension is removed.

This method returns a string which is the extracted filename from the given path. A TypeError is thrown if path is not a string or if suffix is given and is not a string.

The default operation of the path.basename() method varies based on the operating system on which a Node.js application is running. Which means method will take care of both paths '/' (Posix) and '\' (Windows).

path.basename() example in Node.js

basename.js

const path = require('path'); 
console.log('filePath- ', __filename);
const fileName = path.basename(__filename); 
console.log(fileName);

Output

filePath-  D:\NETJS\ NodeJS\nodews\pathdemos\basename.js
basename.js

Here __filename variable is used to get the absolute path of the currently executing file. From that filename is extracted using path.basename() method.

path.basename() with suffix argument

If you pass file extension as the second argument then the extension is removed from the file name.

const path = require('path'); 

console.log('filePath- ', __filename);
console.log('File Extension- ', path.extname(__filename))

const fileName = path.basename(__filename, path.extname(__filename)); 
console.log(fileName);

Output

filePath-  D:\NETJS\NodeJS\nodews\pathdemos\basename.js
File Extension-  .js
basename

Note that path.extname() method is used here to get the extension of the file rather than hardcoding the file extension.

If you have Unix style file paths then also path.basename() method works without any problem.

const path = require('path'); 
const filePath = '/home/netjstech/nodejs/pathdemos/basename.js'
const fileName = path.basename(filePath); 
console.log(fileName);

Output

basename.js

That's all for this topic Node.js path.basename() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Writing a File in Node.js
  2. NodeJS Blocking Non-blocking Code
  3. Appending a File in Node.js

You may also like-

  1. Node.js REPL
  2. Creating HTTP server in Node.js
  3. Setting Wild Card Route in Angular
  4. Custom Pipe in Angular With Example
  5. Java trim(), strip() - Removing Spaces From String
  6. Java Phaser With Examples

__dirname and __filename in Node.js

In this article we'll see what are __dirname and __filename variables in Node.js and how to use them.

__dirname in Node.js

__dirname in Node.js is a convenience variable which stores the absolute path of the directory where the currently executing file (module) resides.

__dirname examples

Suppose project structure is as given below.

myapp
|   app.js
|   package-lock.json
|   package.json  
+---bin 
+---controllers
|       product.js     
+---node_modules         
+---public
|   +---docs      
|   +---images
|   +---javascripts
|   +---stylesheets           
+---routes
|       index.js
|       users.js    
\---views
        error.ejs
        index.ejs

In the app.js if we have the following line of code

console.log('Directory path- ' + __dirname);

then on running the app.js file output is

Directory path- D:\NETJS\NodeJS\nodews\myapp

Which is the absolute path of the directory where app.js file resides.

You can use __dirname in conjunction with path.join() to create paths relative to current file path. For example, if you need to read a file named hello.txt which is inside /public/docs as per the given project structure then you can construct the path using __dirname as given below-

const filePath = path.join(__dirname, "/public/docs/", "hello.txt");
console.log(filePath);
fs.readFile(filePath,'utf8', (err, data) => {
  if(err){
    console.log('Error while reading file');
  }else{
    console.log(data);
  }
});

Output for the filePath is-
D:\NETJS\NodeJS\nodews\myapp\public\docs\hello.txt

__filename in Node.js

__filename in Node.js is a convenience variable which stores the current module file's absolute path.

__filename examples

If we use the same project structure as already mentioned above then having the following lines in app.js

console.log('File Name- ' + __filename);
console.log('Directory path- ' + __dirname);
Gives us the following output
File Name- D:\NETJS\NodeJS\nodews\myapp\app.js
Directory path- D:\NETJS\NodeJS\nodews\myapp

If you want just the file name not the full path then wrap __filename in path.basename() method.

console.log('File Name- ' + path.basename(__filename));

Output

File Name- app.js

That's all for this topic __dirname and __filename in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. Introduction to Node.js
  2. Node.js REPL
  3. Node.js Event Driven Architecture
  4. NodeJS Blocking Non-blocking Code
  5. Appending a File in Node.js

You may also like-

  1. How to Pass Command Line Arguments in Eclipse
  2. String in Java Tutorial
  3. Angular Custom Property Binding Using @Input Decorator
  4. Spring MVC Dropdown Example Using Select, Option And Options Tag

Wednesday, June 12, 2024

Java JDBC Steps to Connect to Database

JDBC API provides a set of interfaces and classes for performing the following tasks-

  • Connecting to database
  • Creating SQL statement
  • Executing created SQL statement in database
  • Returning the results
  • Processing that ResultSet

Steps for connecting any Java application to DB and fetching results using JDBC can be summarized as follows

  • Registering driver class
  • Creating connection to DB
  • Creating Statement
  • Executing Query
  • Processing ResultSet
  • Closing connection

Interfaces provided by JDBC for these steps are-

  1. Driver (That is the interface implemented by the database vendors to provide a JDBC driver for specific databases)
  2. Connection
  3. Statement
  4. ResultSet

Steps for connecting to Database using JDBC

Steps for connecting to Database using JDBC are explained here along with examples to connect to differenct DBs like Oracle, MySql, DB2.

1. Registering driver class

First thing you need to do is to register JDBC driver for the DB you are connecting to. You can use forName() method provided by class Class to load the JDBC driver in order to register it.

General form using Class.forName()

class.forName(“JDBC Driver Class”);

Using registerDriver() method

You can also use registerDriver() method provided by DriverManager class to load the appropriate driver. Note that it is a static method.

General form using registerDriver() method

DriverManager.registerDriver(Driver class object);

Driver classes for some of the databases are as follows -

  • MySql– com.mysql.jdbc.Driver (You need to download MySQL Connector/J jar mysql-connector-java-5.1.39.jar (Please check for the latest version) which will have the JDBC driver).
  • Oracle– oracle.jdbc.driver.OracleDriver (You need to download ojdbc8.jar or higher version for Java 8 and JDBC 4.2).
  • DB2– com.ibm.db2.jcc.DB2Driver (You need to download db2jcc.jar for the DB2 JDBC driver).

Loading Oracle driver using Class.forName() method-

Class.forName(“oracle.jdbc.driver.OracleDriver”);

JVM automatically loads the classes that are used in the program. Since the driver class is not explicitly used in the program that’s why JVM won’t load it automatically. That is the reason you need to load driver class using class.forName() that way you explicitly tell JVM to load this driver class.

Loading MySql driver using resgisterDriver method-

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

If you are using JDBC 4.x (Version Java 6 or higher) then actually you don’t need to explicitly load the JDBC driver. As Automatic loading of JDBC drivers is supported from JDBC 4 you just need to have the appropriate jar in the class path. So loading driver step is optional from Java 6 onwards make sure that automatic loading is supported by the driver you are using.

2. Creating connection object

Once you have registered the driver, second step is to open a connection to the DB. For that you can use the static method getConnection() of the java.sql.DriverManager class.

General form of getConnection method

DriverManager.getConnection(DB_URL, DBuser, password)

URL Pattern for some of the databases

  • Oracle– jdbc:oracle:<drivertype>:@<database>

    As example- Connecting user scott with password tiger to a database with SID orcl through port 1521 of host myhost, using the Thin driver.

    Connection connection = DriverManager.getConnection
         ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");
    
  • MySQL– jdbc:mysql://hostname:portnumber/dbName

    As example- Connecting user root with password admin to a database test through port 3306 of host localhost.

    Connection connection = DriverManager.getConnection
         ("jdbc:mysql://localhost:3306/test", "root", "admin");
    
  • DB2– jdbc:db2://hostname:portnumber/dbName

    As example- Connecting user dbadmin with password dbadmin to a database mydb through port 5021 of host myhost.

    Connection connection = DriverManager.getConnection
         ("jdbc:db2://myhost:5021/mydb","dbadmin","dbadmin");
    

3. Creating Statement object

Once Connection object is created that can be used to create a Statement object. This object is needed for specifying the SQL statement that has to be executed by the DB.

Statement statement = connection.createStatement();

4. Executing Query

To execute a query you need to call execute() method of the Statement class.

You can call executeUpdate(String sql) method for INSERT, DELETE, UPDATE or DDL (Data Definition Language) SQL statements. This method returns an integer representing the number of rows affected by the SQL statement so you will know how many rows are inserted, deleted or updated.

You can call executeQuery(String SQL) method for SELECT sql queries. This method returns a ResultSet.

As example-

  1. To create a table employee
    statement.executeUpdate(“CREATE TABLE employee (id int(11), name varchar(35), age int(11))”);
    
  2. To get data for all employees
    ResultSet rs = statement.executeQuery("Select * from Employee"); 
    

5. Processing ResultSet

Once the query is executed and you have the ResultSet you access the data in a ResultSet object through a cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the cursor is positioned before the first row. You can use next method to move to the next row of the ResultSet. There are various getter methods based on data type to get the value of the current row.

As example-

If you want to iterate the ResultSet returned from the above query for getting all the employees.

while(rs.next()){
 System.out.println("id : " + rs.getInt("id") + " Name : " + rs.getString("name") + " Age : " + rs.getInt("age"));
}

In the example getter method are using the column labels to retrieve the values you can also use the column indexes to get the values, index starts from 1.

while(rs.next()){
 System.out.println("id : " + rs.getInt(1) + " Name : " + rs.getString(2) + " Age : " + rs.getInt(3));
}

6. Closing the connection

Once you have the processed the ResultSet you can close the connection.

connection.close();

It’s better to close an opened connection in a finally block. That ensures that the connection is closed even if there is an exception in the code.

JDBC Connection example

Let’s put all these steps together in a Java example program connecting to MySQL DB using JDBC. DB schema is netjs and table is Employee.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCCon {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      // Another way
      //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
   
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", 
                   "root", "admin");
      // creating Statement
      Statement stmt = connection.createStatement();  
   
      // Executing Query
      ResultSet rs = stmt.executeQuery("Select * from Employee");

      // Processing Resultset
      while(rs.next()){
         System.out.println("id : " + rs.getInt("id") + " Name : " 
          + rs.getString("name") + " Age : " + rs.getInt("age")); 
      }
    
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }finally{
      if(connection != null){
         //closing connection 
         try {
           connection.close();
         } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
    }
  }
}

You can put DB credential information in a properties file and read it from there. Refer How to read Properties file in Java to see how to read properties file in Java.

JDBC Connection to DB using try-with-resources

If you are using Java 7 or above, you can use a try-with-resources statement, when connecting to DB using JDBC, to automatically close Connection, Statement, and ResultSet objects, regardless of whether an SQLException has been thrown.

If we modify the above code to include try-with-resources then we can get rid of finally block used to close the connection.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCCon {
  public static void main(String[] args) {
    try(Connection connection = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/netjs", "root", "admin"))
    {
      // creating Statement
      Statement stmt = connection.createStatement();  

      // Executing Query
      ResultSet rs = stmt.executeQuery("Select * from Employee");
     
      // Processing Resultset
      while(rs.next()){
         System.out.println("id : " + rs.getInt("id") + " Name : " 
               + rs.getString("name") + " Age : " + rs.getInt("age")); 
      }
    }catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Note that Class.forName("com.mysql.jdbc.Driver"); statement is excluded as that is also optional, from JDBC 4.0 drivers which are in the class path are automatically loaded.

That's all for this topic Java JDBC Steps to Connect to DB. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java JDBC overview - JDBC Tutorial
  2. Types of JDBC Drivers
  3. PreparedStatement Interface in Java-JDBC
  4. DataSource in Java-JDBC
  5. Spring JdbcTemplate Insert, Update And Delete Example

You may also like-

  1. How to Remove Duplicate Elements From an ArrayList in Java
  2. ConcurrentHashMap in Java With Examples
  3. Lambda Expressions in Java 8
  4. Transient Keyword in Java With Examples
  5. Spring NamedParameterJdbcTemplate Select Query Example
  6. Race Condition in Java Multi-Threading
  7. Angular Template-Driven Form Validation Example
  8. Node.js Event Driven Architecture

Tuesday, June 11, 2024

Bean Scopes in Spring With Examples

In this post we'll see different bean scopes provided by the Spring framework.

When you create a bean definition, you provide a configuration for creating actual instances of the class defined by that bean definition. By providing bean definition you can control not only, the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition.


Spring Bean Scope Description

Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports six bean scopes.

  1. singleton- Scopes a single bean definition to a single object instance per Spring IoC container. This is the default scope in Spring which means if you don't provide any scope Spring will consider the bean to have singleton scope.
  2. prototype- Prototype scope for a bean results in the creation of a new bean instance every time a request for that specific bean is made.
  3. request- Scopes a single bean definition to the life cycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
  4. session- Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  5. application- Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
  6. websocket- Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

Singleton Scope in Spring

If you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

The singleton scope is the default bean scope in Spring. To define a bean as a singleton in XML, you would write, for example:

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>
If you want to define bean scope using annotation then you can use @Scope annotation along with the required scope.
@Service
@Scope("singleton")
public class DefaultAccountService{
 ...
 ...
}

Prototype scope in Spring

When you define a bean and provide prototype scope that results in the creation of a new bean instance every time a request for that specific bean is made.

Following example defines a bean with scope as prototype in XML:

<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
Using @Scope annotation same thing can be written as-
@Component
@Scope("prototype")
public class DefaultAccountService {
 ...
 ...
}

Note that Spring does not manage the complete life cycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization life cycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

Request scope in Spring

If a bean is defined with scope as request, it means Spring container creates a new instance of that bean by using the bean definition for each and every HTTP request.

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

When using annotation-driven components or Java configuration, the @RequestScope annotation (available from Spring 4) can be used to assign a component to the request scope or @Scope(WebApplicationContext.SCOPE_REQUEST).

@RequestScope
@Component
public class AccountLogin {
 ...
 ...
}

When the request completes processing, the bean that is scoped to the request is discarded.

Session Scope in Spring

If a bean is defined with scope as session the Spring container creates a new instance of the that bean by using the bean definition for the lifetime of a single HTTP Session. So the created bean instance is effectively scoped at the HTTP Session level.

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
When using annotation-driven components or Java configuration, you can use the @SessionScope annotation (available from Spring 4) to assign a component to the session scope or @Scope(WebApplicationContext.SCOPE_SESSION).
@SessionScope
@Component
public class UserPreferences {
  ...
  ...
}

When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.

Application scope in Spring

If a bean is defined with the scope as application, then the Spring container creates a new instance of the bean by using that bean's definition once for the entire web application.

<bean id="appPreferences" class="com.foo.AppPreferences" scope="application"/>
When using annotation-driven components or Java configuration, you can use the @ApplicationScope annotation (available from Spring 4) to assign a component to the application scope or @Scope(WebApplicationContext.SCOPE_APPLICATION).
@ApplicationScope
@Component
public class AppPreferences {
  ...
  ...
}

The bean is scoped at the ServletContext level, stored as a regular ServletContext attribute.

WebSocket scope in Spring

The Spring Framework provides a WebSocket API that you can use to write client- and server-side applications that handle WebSocket messages. You can declare a Spring-managed bean in the websocket scope. Those are typically singletons and live longer than any individual WebSocket session.

<bean id="appPreferences" class="com.foo.AppPreferences" scope="websocket"/>
Using @Scope annotation same thing can be written as-
@Component
@Scope("websocket")
public class MyBean {
  ...
  ...
}

Note that the request, session, application, and websocket scopes are available only if you use a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you use these scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext, you get an IllegalStateException complaining about an unknown bean scope.

That's all for this topic Bean Scopes in Spring With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Dependency Injection in Spring Framework
  2. Bean Definition Inheritance in Spring
  3. How to Inject Prototype Scoped Bean in Singleton Bean
  4. Spring MessageSource Internationalization (i18n) Support
  5. @Required Annotation in Spring Framework

You may also like-

  1. Spring Java Configuration Example Using @Configuration
  2. Injecting Inner Bean in Spring
  3. Configuring DataSource in Spring Framework
  4. Dependency Injection Using factory-method in Spring
  5. Count Number of Words in a String Java Program
  6. @FunctionalInterface Annotation in Java
  7. How to Sort an ArrayList in Descending Order in Java
  8. Polymorphism in Java

Monday, June 10, 2024

JDBC Tutorial - Java JDBC Overview

This JDBC tutorial gives an overview of JDBC which is the Java API for developing Java applications that access relational databases.

Why use JDBC

JDBC provides developers with a uniform interface to connect with different relational databases like Oracle, MySQL, DB2, Access etc.

JDBC provides a set of interfaces and classes that standardize the interaction with different databases and abstracts you as a developer with the inner working of the proprietary databases. You just need to know the standard JDBC steps to connect to database, query it in order to fetch results or update DB. Note here that the SQL may differ according to the DB used.

JDBC Drivers

In Order to connect to database JDBC uses JDBC drivers. Since JDBC driver acts as a connector between JDBC and proprietary databases JDBC drivers are DB specific and generally provided by the DB vendor itself.

As example– In order to connect to MySql DB you will need a MySql JDBC connector driver which is bundled in the mysql-connector-javaXXX.jar.

The interaction of JDBC with the database using JDBC driver can be pictorially represented as follows-

JDBC Drivers

Packages in JDBC API

The JDBC API is comprised of two packages:

  • java.sql- Referred to as the JDBC core API
  • javax.sql- Referred to as the JDBC Optional Package API

You automatically get both packages when you download the Java Platform Standard Edition (Java SE).

Changes in JDBC 4.x

The current version of JDBC which comes bundled with Java is JDBC 4.3. There are some noticeable changes in the 4.x versions like-

  1. Addition of the java.sql.SQLType Interface
  2. Addition of the java.sql.JDBCType Enum– Using SQLType interface and JDBCType Enum you can identify the generic SQL types like CLOB, REF_CURSOR, TINYINT, VARCHAR etc.
  3. You can use try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement.
  4. Automatic loading of JDBC drivers on the class path.

Steps for connecting to DB using JDBC

JDBC API provides a set of interfaces and classes for connecting to DB, creating SQL statement, executing created SQL statement in database, returning the results and processing that ResultSet.

These steps can be summarized as follows-

  • Loading driver
  • Creating connection to DB
  • Creating Statement
  • Executing Query
  • Processing ResultSet
  • Closing connection

Refer Java JDBC Steps to Connect to DB to see these steps in details and a JDBC example Java program.

A pictorial representation of these steps can be represented as follows.

JDBC DB connection steps

That's all for this topic JDBC Tutorial - Java JDBC Overview. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Connection Interface in Java-JDBC
  2. Statement Interface in Java-JDBC
  3. Transaction in Java-JDBC
  4. DataSource in Java-JDBC
  5. Data access in Spring framework

You may also like-

  1. Interface Default Methods in Java 8
  2. PermGen Space Removal in Java 8
  3. How ArrayList Works Internally in Java
  4. Difference Between CountDownLatch And CyclicBarrier in Java
  5. Java Object Cloning - clone() Method
  6. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  7. Arrange Non-Negative Integers to Form Largest Number - Java Program
  8. Best Practices For Exception Handling in Java

Sunday, June 9, 2024

Connection Interface in Java-JDBC

In the post Java JDBC Steps to Connect to DB we have already seen a complete example using the interfaces Driver, Connection, Statement and ResultSet provided by the JDBC API. In this post we’ll see Java Connection interface in detail.

Connection interface in JDBC

Connection interface resides in java.sql package and it represents a session with a specific database you are connecting to. SQL statements that you want to execute, results that are returned all that happens with in the context of a connection.

You can get a Connection object by using the getConnection() method of the DriverManager class.

Using Connection class object-

  • You can get an object of Statement.
  • You can get the information about the database (DatabaseMetaData) it is connecting to.
  • Connection also provides method for transaction management like commit(), rollback().

Fields in the Connection interface

Connection interface provides a set of fields for specifying transaction isolation level-

  • TRANSACTION_NONE- A constant indicating that transactions are not supported.
  • TRANSACTION_READ_COMMITTED- A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
  • TRANSACTION_READ_UNCOMMITTED- A constant indicating that dirty reads, non-repeatable reads and phantom reads can occur.
  • TRANSACTION_REPEATABLE_READ- A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
  • TRANSACTION_SERIALIZABLE- A constant indicating that dirty reads, non-repeatable reads and phantom reads are prevented.

Frequently used methods of the Connection

Some of the frequently used methods of the Connection are as follows-

For creating statement

There are also overloaded variant of these methods where you can specify the type of ResultSet and its concurrency level.

For getting information about the DB

  • getMetaData()- Returns a DatabaseMetaData object containing metadata about the connected database.

See example of using DatabaseMetaData here- DatabaseMetaData Interface in Java-JDBC.

For transaction management

  • setAutoCommit(boolean autoCommit)- Sets this connection's commit mode to true or false.
  • setTransactionIsolation(int level)- Attempts to changes the transaction isolation level for this Connection object to the one given.
  • rollback()- Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
  • commit()- Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.

See details of Transaction management using JDBC here- Transaction in Java-JDBC.

Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.sql/java/sql/Connection.html

That's all for this topic Connection Interface in Java-JDBC. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java JDBC overview - JDBC Tutorial
  2. CallableStatement Interface in Java-JDBC
  3. Transaction Management in Java-JDBC
  4. DataSource in Java-JDBC
  5. Data Access in Spring Framework

You may also like-

  1. Java Program to Get All DB Schemas
  2. final Vs finally Vs finalize in Java
  3. How to create immutable class in Java
  4. BigDecimal in Java With Examples
  5. Heap Memory Allocation in Java
  6. Reflection in Java - Class
  7. Serialization Proxy Pattern in Java
  8. Spring JdbcTemplate Select Query Example

Friday, June 7, 2024

Appending a File in Node.js

In the post Writing a File in Node.js we saw how to use methods of fs module to write to a file. When you use writeFile() method it rewrites the file if file already exists. If you need to append to a file then fs module has methods to do that too.

How to append to a file in Node.js

In the fs module there are both synchronous and asynchronous methods to append to a file. Description is as given below.

  1. fs.appendFile()- This method asynchronously appends data to a file, creating the file if it does not yet exist. A callback function is provided which is called when the file append operation is completed.
  2. fs.appendFileSync- This method synchronously appends data to a file, creating the file if it does not yet exist.
  3. fsPromises.appendFile()- This method is in the fs.promises API which asynchronously appends data to a file, creating the file if it does not yet exist. Method returns a Promise object which is resolved with undefined upon success.

Using fs.appendFile()

Syntax of fs.appendFile() method is as given below.

fs.appendFile(path, data, options, callback)

The four parameters are described below-

  1. file- Path to the file where content has to be written or file descriptor (a number returned by opening the file using the open() method).
  2. data- Content to be written to the file. It can be of type string or Buffer.
  3. options- It specifies optional parameters that can be provided with write operation. Type can be either string or object. Optional parameters are described below-
    • encoding- A string value specifying the encoding of the file. Default is 'utf8'
    • mode- An integer value specifying the file mode. Default is 0o666 which means both read and write.
    • flag- Flag used in append operation. Default flag is 'a' which means open file for appending. The file is created if it does not exist.
    • flush- If true, the underlying file descriptor is flushed prior to closing it. Default value is false.
  4. callback- A function that is called when the file operation completes. Takes one argument err which denotes the error that can be thrown if append operation fails.

fs.appendFile () Example

const fs = require('fs');
var os = require("os");
const path = require('path');

const content = 'This is a line added to the file' + os.EOL;
fs.appendFile(path.join(__dirname, 'Hello.txt'), content, (err) => {
    if(err){
        console.error(err);
    }else {
        console.log("Append operation completed");
    }
})

Here os.EOL const of the 'os' module is used to add new line at the end.

Using fs.appendFileSync()

Syntax of fs.appendFileSync() method is as given below

fs.appendFileSync(path, data, options)

Description of parameters is similar to fs.appendFile()

fs.appendFileSync() Example

const fs = require('fs');
var os = require("os");
const path = require('path');

const content = 'This is a line added to the file' + os.EOL;
fs.appendFileSync(path.join(__dirname, 'Hello.txt'), content);
console.log("Append operation completed");

Using fsPromises.appendFile()

Syntax of fsPromises.appendFile() method is as given below

fsPromises.appendFile(path, data, options)

Description of parameters is similar to fs.appendFile() method as given above.

fsPromises.appendFile() example

const fs = require('fs');
const fspromises = fs.promises;
var os = require("os");
const path = require('path');

// uses async/await
const appendFile =  async (filePath) => {
    try{
        const content = 'This is a line added to the file' + os.EOL;
        await fspromises.appendFile(filePath, content);
        console.log("Append operation completed");
    } catch(error){
        console.error(err);
    }
}

// function call
appendFile(path.join(__dirname, 'Hello.txt'));

That's all for this topic Appending a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading a File in Node.js
  2. NodeJS Event Loop
  3. NodeJS Blocking Non-blocking Code
  4. Node.js REPL
  5. NodeJS NPM Package Manager

You may also like-

  1. Matrix Addition Java Program
  2. String in Java Tutorial
  3. JavaScript Arrow Function With Examples
  4. Angular Two-Way Data Binding With Examples
  5. Passing Arguments to getBean() Method in Spring