Home Tutorial Java Core JDBC: Select Database Example

 
 

JDBC: Select Database Example
Posted on: September 21, 2012 at 12:00 AM
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:
jdbc:mysql://[host][:port]/[database][?property1][=value1]...

  • host :The host name where MySQL server is running. Default is 127.0.0.1 - 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 {
Class.forName(driverName);
con = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Successfully connected to the database.");
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

Output :

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

Related Tags for JDBC: Select Database Example:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.