How to read input through keyboard in Java

This tutorial shows how to read input from keyword using Java programming language. For example if your database connection string changes then you don’t need to worry because for any database connection string like username and password, this will still work.

This is a simple example, you can customize as per your need. You can also apply validation on each user’s input. Basic idea behind this example how you can read input from keyboard in Java.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ReadDBSettings {
  /**
   * @param args
   */
  public static void main(String[] args) {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String connectionURL = null;
    String username = null;
    String password = null;
    try {
      System.out.print("Enter your DB connection URL: ");
      connectionURL = br.readLine();
      System.out.print("Enter your DB username: ");
      username = br.readLine();
      System.out.print("Enter your DB password: ");
      password = br.readLine();
      System.out.println("connectonURL:" + connectionURL + ", username:" + username + ", password:" + password);
      try {
        Connection conn = getDBConnection(connectionURL, username, password);
        //do code with your connection
      } catch (SQLException e) {
        e.printStackTrace();
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
      System.exit(1);
    }
  }
  public static Connection getDBConnection(String connectionURL, String username, String password) throws SQLException {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      return DriverManager.getConnection("jdbc:mysql://" + connectionURL, username, password);
    } catch (ClassNotFoundException e) {
      throw new SQLException(e.getMessage());
    }
  }
}

Thanks for reading.

Related posts

Leave a Comment