This tutorial shows how to read input from keyword using java. This example shows also if your database connection string changes then also you don’t need to worry because for any database connection string, username and password this will work.
This is a simple example, you can customize as per your need. You can also apply validation on each field while user inputs. 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 your reading. Comments improve us, so please leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *