In this tutorial we will learn What is Connection class in java JDBC.
- Connection class is found in java.sql package in java JDBC.
- java.sql.Connection helps in establishing connection/session with database in java JDBC.
- java.sql.Connection extends java.lang.AutoCloseable interface from which java 7
- Important methods of java.sql.Connection class in java JDBC >
- Database information related methods of java.sql.Connection class in java JDBC >-
- getMetaData - Method returns DatabaseMetaData. DatabaseMetaData can be used to obtain information about the database as a whole.
- Transaction related methods of java.sql.Connection class in java JDBC >
- setAutoCommit(boolean autoCommit) = for setting autocommit mode of transactions in java JDBC
- commit() - method can be used to commit the transactions in java JDBC.
- rollback() - method can be used to rollback the transactions in java JDBC.
- close() - It closes the connection
- Statement related methods of java.sql.Connection class in java JDBC >
- createStatement()
- prepareStatement(String sql)
For more detail on how to use java.sql.Connection class in java program. Read : JDBC connection with Oracle 11g - ojdbc6.jar - configure java build path - registering driver - getConnection - Writing your First jdbc program
Connection class - Example/ Full program to connect to Oracle database using Type 4 driver - java JDBC program >
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ConnectionClassExample {
public static void main(String... arg) {
Connection con =null;
try {
// registering Oracle driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// getting connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"ankit", "Oracle123");
// Test connection is null or not
if (con != null)
System.out.println("Connection established successfully!");
else
System.out.println("No Connection!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(con!=null) con.close(); // close connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*OUTPUT
Connection established successfully!
*/
|
Also read more program and example on how to create connection with following databases >
JDBC connection with Oracle 11g
JDBC connection with MySql database
JDBC connection with MsSql (Microsoft) database
JDBC connection with PostgreSQL database
So, In this tutorial we learned about what is java.sql.Connection class in java.