JDBC is a Java API that can perform database processing (SQL statements). There are java.sql (core: J2SE), javax.sql (standard extension: J2EE) and so on.
Below is an example using java.sql.
import java.sql.*;
public class class name{
public static void main(String args[])
throws SQLException, ClassNotFoundException { //Exception handling For displaying error pages
String drv = "oracle.jdbc.OracleDriver"; // Oracle JDBC (Type4)Specify
String url = "jdbc:oracle:thin:@localhost:1521:Database name"; //Database url
Class.forName(drv); //Load the driver
Connection con = DriverManager.getConnection(url,User name,password); //Connect to database
Statement stmt = con.createStatement(); //Preparing for inquiries
String qry = "SQL statement for example SELECT*FROM table name"; //Query preparation
ResultSet rs = stmt.executeQuery(qry); //Execute SQL statement and receive result as ResultSet
//ResltSet data income line by line
while(rs.next()){ // next()Specify each row in the method and return false when the table is finished.
String Column name 1= rs.getString("Column name 1");
Int column name 2= rs.getInt("Column name");
System.out.println(Column name 1+ "\t" +Column name 2); //display
}
//Close connection with database
rs.close();
stmt.close();
con.close();
}
}
If you want to receive input and insert it into SQL statement, the notation such as preparation of SQL statement changes.
import java.sql.*;
public class class name{
public static void main(String args[])
throws SQLException, ClassNotFoundException { //Exception handling For displaying error pages
String drv = "oracle.jdbc.OracleDriver"; // Oracle JDBC (Type4)Specify
String url = "jdbc:oracle:thin:@localhost:1521:Database name"; //Database url
Class.forName(drv); //Load the driver
Connection con = DriverManager.getConnection(url,User name,password); //Connect to database
String qry = "SQL statement for example SELECT*FROM table name where column name= ?AND column name= ?";
// ?The input value is inserted in the part of. 1 from the left,Specify with 2 and a number.
PreparedStatement ps = con.prepareStatement(qry); //Preparing for inquiries
ps.setString(1,Input 1); //1st?Insert input into. If the input is a string.
ps.setInt(2,Input 2); //Second?Insert input into. If the input is an integer type.
ResultSet rs = ps.executeQuery(); //Execute SQL statement and receive result as ResultSet
//ResltSet data income line by line
while(rs.next()){ // next()Specify each row in the method and return false when the table is finished.
String Column name 1= rs.getString("Column name 1");
Int column name 2= rs.getInt("Column name");
System.out.println(Column name 1+ "\t" +Column name 2); //display
}
//Close connection with database
rs.close();
ps.close();
con.close();
}
}
Recommended Posts