Monday, August 26, 2024

Node.js MySQL Delete Example

In the post Node.js MySQL Update Example we saw examples of updating records in a table using Node.js and MySQL. In this post we'll see examples of deleting records from table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


CREATE TABLE `node`.`employee` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `join_date` DATE NOT NULL,
  `age` INT NULL,
  PRIMARY KEY (`id`));

Node.js delete record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'admin',
    database: 'node',
    waitForConnections: true, 
    connectionLimit: 10,
  });

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to delete Employee record from employee table in MySQL DB.

const pool = require('./util/database');

async function deleteEmployee(id){
  // TODO Verify if emp with the same id exists or not.. 
  // For that select query to get by id can be used

  const sql = "DELETE FROM EMPLOYEE where id = ?";
  const values = [id];
    try{
      const conn = await pool.getConnection();
      const [result, fields] = await conn.execute(sql, values);
      console.log(result);
      console.log(fields);
      conn.release();
    }catch(err){
      console.log(err);
    }
}

deleteEmployee(1);

Important points to note here-

  • deleteEmployee() function is an async function as we are using async/await (Promise based API) rather than callback-based API.
  • We are using await with pool.getConnection() method.
  • deleteEmployee() function takes one argument where it expects an id for the employee to be deleted.
  • Delete query is created as a parameterized query, where id is passed later. By having this kind of prepared statement makes our code more generic to be used with any id and also gives better performance.
  • By using array destructuring we get the returned values for result and fields.
  • fields variable contains extra meta data about results, if available.
  • result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  • After the task, connection is released using conn.release() which means connection goes back to the pool.

On running the file-

>node app.js

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  info: '',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 0
}

undefined

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


Related Topics

  1. Node.js MySQL Insert Example
  2. Node.js MySQL Select Statement Example
  3. Node.js - MySQL Connection Pool

You may also like-

  1. Node.js path.resolve() Method
  2. NodeJS Event Loop
  3. Node.js Event Driven Architecture
  4. How to Setup a Node.js Project
  5. Custom Async Validator in Angular Reactive Form
  6. Pre-defined Functional Interfaces in Java
  7. Java Program to Convert a File to Byte Array
  8. JavaScript let and const With Examples

Saturday, August 24, 2024

Node.js MySQL Update Example

In the post Node.js MySQL Insert Example we have seen how to do an insert in MySQL DB from Node.js application. In this post we'll see examples of updating records in a table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Refer Node.js - MySQL Connection Pool to get more information about using MySQL Connection Pool with Node.js

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


CREATE TABLE `node`.`employee` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `join_date` DATE NOT NULL,
  `age` INT NULL,
  PRIMARY KEY (`id`));

Node.js update record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'admin',
    database: 'node',
    waitForConnections: true, 
    connectionLimit: 10,
  });

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to update Employee record in MySQL.

const pool = require('./util/database');

async function updateEmployee(emp){
  // Verify if emp with the same id exists or not
  // For that select query to get by id can be used

  const sql = "UPDATE EMPLOYEE set name = ?, join_date = ?, age = ? where id = ?";
  const values = [emp.name, emp.joinDate, emp.age, emp.id];
    try{
      const conn = await pool.getConnection();
      const [result, fields] = await conn.execute(sql, values);
      console.log(result);
      console.log(fields);
      conn.release();
    }catch(err){
      console.log(err);
    }
}

//calling function with employee object
updateEmployee({name:'Ishan', joinDate:'2024-04-23', age:28, id:1})

Important points to note here-

  1. updateEmployee() function is an async function as we are using async/await (Promise based API) rather than callback-based API.
  2. We are using await with pool.getConnection() method.
  3. updateEmployee() function takes one argument where it expects an employee object to be passed.
  4. Using that object, appropriate values are passed to the prepared statement to update a record.
  5. By using array destructuring we get the returned values for result and fields.
  6. fields variable contains extra meta data about results, if available.
  7. result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  8. After the task, connection is released using conn.release() which means connection goes back to the pool.

On running the file-

>node app.js

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  info: 'Rows matched: 1  Changed: 1  Warnings: 0',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 1
}

Undefined

If you want to get the number of rows which are updated you can get it using result.affectedRows from the result object.

You can check the DB to see the updated values.

Node.js MySQL Update

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


Related Topics

  1. Node.js MySQL Select Statement Example
  2. Node.js MySQL Delete Example
  3. Node.js - Connect to MySQL Promise API

You may also like-

  1. Node.js path.basename() Method With Examples
  2. __dirname and __filename in Node.js
  3. Appending a File in Node.js
  4. Creating HTTP server in Node.js
  5. Service in Angular With Examples
  6. Java Stream - count() With Examples
  7. Why main Method static in Java
  8. Named Tuple in Python

Convert String to Byte Array Java Program

In this post we'll see a Java program to convert a String to byte array and byte array to String in Java.


Converting String to byte[] in Java

String class has getBytes() method which can be used to convert String to byte array in Java.

getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

There are two other variants of getBytes() method in order to provide an encoding for String.

  • getBytes(Charset charset)
  • getBytes(String charsetName)
import java.util.Arrays;

public class StringToByte {
 public static void main(String[] args) {
  String str = "Example String";
  byte[] b = str.getBytes();
  System.out.println("Array " + b);
  System.out.println("Array as String" + Arrays.toString(b));
 }
}

Output

Array [B@2a139a55
Array as String[69, 120, 97, 109, 112, 108, 101, 32, 83, 116, 114, 105, 110, 103]

As you can see here printing the byte array gives the memory address so used Arrays.toString in order to print the array values.

Conversion of string to byte array with encoding

Suppose you want to use "UTF-8" encoding then it can be done in 3 ways.

String str = "Example String";
byte[] b;
try {
 b = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
b = str.getBytes(Charset.forName("UTF-8"));
b = str.getBytes(StandardCharsets.UTF_8);

Using str.getBytes("UTF-8") method to convert String to byte array will require to enclose it in a try-catch block as UnsupportedEncodingException is thrown. To avoid that you can use str.getBytes(Charset.forName("UTF-8")) method. Java 7 onward you can also use str.getBytes(StandardCharsets.UTF_8);

Converting byte array to String in Java

String class has a constructor which takes byte array as an argument. Using that you can get the String from a byte array.

String(byte[] bytes)- Constructs a new String by decoding the specified array of bytes using the platform's default charset.

If you want to provide a specific encoding then you can use the following constructor-

String(byte[] bytes, Charset charset)- Constructs a new String by decoding the specified array of bytes using the specified charset.

public class StringToByte {
 public static void main(String[] args) {
  String str = "Example String";
  // converting to byte array
  byte[] b = str.getBytes();
  
  // Getting the string from a byte array
  String s = new String (b);
  System.out.println("String - " + s);
 }
}

Output

String - Example String

That's all for this topic Convert String to Byte Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to int in Java
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Add Double Quotes to a String Java Program

You may also like-

  1. Find Duplicate Elements in an Array Java Program
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Association, Aggregation and Composition in Java
  4. Difference Between Abstract Class And Interface in Java
  5. Multi-Catch Statement in Java Exception Handling
  6. How ArrayList Works Internally in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Java ThreadLocal Class With Examples

Friday, August 23, 2024

Creating Custom Exception Class in Java

In this post we'll see how to create a custom exception in Java.

custom exception in Java

Though Java's exception handling covers the whole gamut of errors and most of the time it is recommended that you should go with standard exceptions rather than creating your own custom exception classes in Java, but you might need to create custom exception types to handle situations which are specific to your application.

Tuesday, August 20, 2024

Count Number of Words in a String Java Program

Write a Java program to count the number of words in a String is asked quite frequently in Java interviews. To test the logical thinking of the candidates it is often asked to write this program without using any of the String functions.

Java Program to count number of words in a String

Here three ways are given to count number of words in a String in Java. All of these ways take care of any number of spaces in between the words even the spaces at the beginning or at the end.

  • First method countWords() uses charAt() method to get each character of the String. Logic used in the method works fine even if there are extra spaces in the passed String and the correct count of the words in the String is given.
  • Second method countWordsUsingSplit() uses the String split() method to count number of words.
  • Third method countWordsUsingStream() uses the Java Stream API to count number of words.

Let's see the Java code first and later explanation of the code logic.

public class StringWordCount {
  public static void main(String[] args) {
    System.out.println("Word Count- " + countWords("   Life    is    beautiful  "));
        
    System.out.println("Count using split logic " + countWordsUsingSplit("         Life     is       beautiful  "));
    
    System.out.println("Count using Java Stream " + countWordsUsingStream("   Life    is    beautiful  "));
  }
    
  private static int countWords(String str){        
    
    if(str.isBlank()) {
      return 0;
    }
    int c = 0;
    for(int i = 0; i < str.length(); i++){
     
      /**
       * logic here is if the current character is not a space and the character read before the 
       * current char was a space that means one whole word is read so increment the count.  
       * Or part is to ensure correct working even if there are spaces in the beginning
      */
      if((i > 0 && (str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' ))
          || ((i == 0) && (str.charAt(0) != ' ')))
        c++;
    }
    return c;
  }
    
  /**
  * This method counts using String split method 
  * @param str
  * @return
  */
  private static int countWordsUsingSplit(String str){
    // here split method is used with regex pattern of any number of spaces
    // so it will retrun a string array with the words
    String[] test = str.trim().split("\\s+");
    return test.length;
  }
  
  /**
  * This method counts using Java Stream API
  * @param str
  * @return
  */
  private static long countWordsUsingStream(String str){
	  // here split method is used with regex pattern of any number of spaces
	  // trim() is used to remove spaces in the beginning and at the end
	  long count = Stream.of(str.trim().split("\\s+")).count();
	  
	  return count;
  }
}

Output

Word Count- 3
Count using split logic 3
Count using Java Stream 3

Count number of words in a String program logic

In the first method countWords() the idea is; if the current character is not a space and the character read before the current char was a space that means one whole word is read so increment the count. This is the condition doing that

(str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' )

For example if program is reading the string “life is” when the index comes to 'i' (in "is") the character before 'i' would be either space or tab, that means one word is already read (which in this case would be "life") thus count will be incremented.

We may miss to count the first word, this condition (i == 0) && (str.charAt(0) != ' ')) takes care of that.

Second way of counting number of words in a String uses the split method of string. Split() method takes a regex pattern as a parameter here we are passing “//s+” which will mean any number of spaces. So the condition becomes; split the word on any number of spaces in between. It returns a String array whose length will be the count of words in a string.

In the third method, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then count() method of Java Stream API is used to return the count of elements in this stream.

That's all for this topic Count Number of Words in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Java Program to Check Prime Number

You may also like-

  1. Bubble Sort Program in Java
  2. Matrix Subtraction Java Program
  3. Package in Java
  4. Encapsulation in Java
  5. Marker interface in Java
  6. Creating Custom Exception Class in Java
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Race Condition in Java Multi-Threading

Friday, August 16, 2024

Java Semaphore With Examples

Semaphore is one of the synchronization aid provided by Java concurrency util in Java 5 along with other synchronization aids like CountDownLatch, CyclicBarrier, Phaser and Exchanger.

The Semaphore class present in java.util.concurrent package is a counting semaphore in which a semaphore, conceptually, maintains a set of permits. Semaphore class in Java has two methods that make use of permits-

  • acquire()- Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. It has another overloaded version acquire(int permits).
  • release()- Releases a permit, returning it to the semaphore. It has another overloaded method release(int permits).

Thursday, August 15, 2024

Java Exchanger With Examples

Exchanger in Java is one of the Synchronization class added along with other synchronization classes like CyclicBarrier, CountDownLatch, Semaphore and Phaser in java.util.concurrent package.

How does Exchanger in Java work

Exchanger makes it easy for two threads to exchange data between themselves. Exchanger provides a synchronization point at which two threads can pair and swap elements. Exchanger waits until two separate threads call its exchange() method. When two threads have called the exchange() method, Exchanger will swap the objects presented by the threads.