JDBC - Java Database Connectivity.
Examples Included:
- Create a Database connection.
- Fetch Data from Database table in your Java class.
- Insert Data from Java Code into Database Table
Git Location:
https://github.com/studyskymate/WebProject/tree/master/src/com/studyskymate/dinesh/java/login
Note: Presentation download Link at the end of this page.
https://github.com/studyskymate/WebProject/tree/master/src/com/studyskymate/dinesh/java/login
Note: Presentation download Link at the end of this page.
Example:
LoginJDBC.java
package com.studyskymate.dinesh.java.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class LoginJDBC {
public static void main(String[] args) {
try {
//Registering the Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Creating connection
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@CEIT-SRV1.fnu.local:1521/orcl.fnu.local","hr","hr");
//Creating Statement
Statement statement=con.createStatement();
//Execute Query
ResultSet rs =statement.executeQuery("select * from Employee");
while(rs.next()) {
System.out.println(
rs.getInt(1)+" "+rs.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Check the Database for connection
Check the table to Query:
For Example, I want to query on Employee Table
You need ojdbc.jar to be linked in your project to have a connection to the database.
Download the jar from below location and add in the library path of your project
http://www.java2s.com/Code/Jar/o/Downloadojdbc14jar.htm
Run your Java Class to check the connection.
Check the Result:
Below data is displayed as transferred from Table:
Code for Insert into Employee Table:
InsertDataEx.java
package com.studyskymate.dinesh.java.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertDataEx {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@CEIT-SRV-1.fnu.local:1521/orcl.fnu.local","hr","hr");
Statement statement=con.createStatement();
int result= statement.executeUpdate("INSERT INTO EMPLOYEE VALUES
('506','Dinesh')");
System.out.println("result: "+result);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}