how to create jdbc connection in java code example
Example 1: create jdbc connection in java
package com.java2novice.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConnection {
public static void main(String a[]){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.
getConnection("jdbc:oracle:thin:@::"
,"user","password");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Example 2: how to create jdbc connection in java
Connection =
Helps our java project connect to database
Statement =
Helps to write and execute SQL query
ResultSet =
A DataStructure where the data from query result stored
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
After succesfully created the connect
next step is STATEMENT
Statement statement = connection.createStatement();
We use createStatement() method to create
the statement from our connection.
-The result we get from this type of statement
can only move from top to bottom,
not other way around
Statement statement = connection.
createStatement(ResultSet TYPE_SCROLL_INSENSITIVE
,ResultSet CONCUR_READ_ONLY);
-The result we get from this type of
statement can freely move between rows
Once we have statement we can run
the query and get the result to
ResultSet format
import java.sql.ResultSet;
We use the method executeQuery()
to execute our queries
ResultSet result = statement.
executeQuery("Select * from employees");