Share on Google+Share on Google+

JDBC: Select Database Example

In this section, we will discuss how to select database using JDBC with example.

JDBC: Select Database Example

In this section, we will discuss how to select database using JDBC with example.

Select Database :

JDBC API provides a simple way to handle the database and execute the common sql query. Database is collection of data. You specify tables to the database.
So whenever you required to perform any operation in to your table, it is required to select the corresponding database. For that create connection to the database.

For selecting database we need to understand some terms which are important in creation of database connection.

Connection: This  interface specifies connection with specific databases like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of this interface.

Class.forName(String driver): It loads the driver.

DriverManager  :  The DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property

getConnection(String url+dbName, String userName, String password): This method establishes a connection to specified database url.

The MySQL connection URL has the following format:

  • host :The host name where MySQL server is running. Default is - the IP address of localhost.
  • port : The port number where MySQL is listening for connection. Default is 3306.
  • dbName : The name of an existing database on MySQL server. If not specified, the connection starts no current database.
  • Property : The name of a supported connection properties. "userName" and "password" are 2 most important properties.

Example :

In this example we are selecting database students. For that we are creating connection using JDBC API.

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

class SelectDatabase{
public static void main(String[] args){
System.out.println("Select database Example...");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "students";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
con = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Successfully connected to the database.");
}catch (Exception e) {

Output :

Select database Example...
Successfully connected to the database.


Posted on: September 21, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.