Get the connection from the Database
- To get the connection, we need to call getConnection() method.
- getConnection() method is presents in java.sql.DriverManager class
Syntax
public static Connection
getConnection(String url,String username, String password) throws SQLException
- url = jdbc:oracle:thin:@localhost:1521:xe
- Oracle Data base user name = scott
- Oracle Data base password = tiger
Example
Connection con = DriverManager("jdbc:oracle:thin:@localhost:1521:xe","system","nireekshan");
From jdbc:oracle:thin:@localhost:1521:xe
- jdbc is the JDBC API,
- oracle is name of the database,
- thin is name of the driver,
- localhost is name of the server on which oracle is running,
- 1521 is port number
- xe is name of the Oracle Service name.
-------------------------------------------------------------------------------------
Program name : DBConnect1.java
Output :
Driver is Registered successfully
got Connection from DB success
got Connection from DB success
import java.sql.*;
class DBConnect2
{
public static void
main(String args[])throws SQLException
{
//step-1:Register the JDBC driver
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
System.out.println(“Driver is Registered successfully”);
//step-2: get the connection from DB server
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","nireekshan");
System.out.println("got Connection from
DB success"+con);
}
}
Note:
To compile above java program we have to set the class path to ojdbc14.jar, so, keep this jar in corresponding directory then set the class path.
Set class path:
- C:\Nireekshan\JDBC>set classpath=ojdbc14.jar;.;
Compile : javac DBConnect1.java
Run : java DBConnect1
Output :
Driver is Registered successfully
got Connection from DB success
got Connection from DB success
-------------------------------------------------------------------------------------
Thanks for your time.
Thanks for your time.
Nireekshan