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.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(;
    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) {
    } catch (IOException ioe) {
  public static Connection getDBConnection(String connectionURL, String username, String password) throws SQLException {
    try {
      return DriverManager.getConnection("jdbc:mysql://" + connectionURL, username, password);
    } catch (ClassNotFoundException e) {
      throw new SQLException(e.getMessage());

Thanks for reading.

Leave a Comment