JDBC mean Java Database Connectivity. In java, using JDBC drivers, we can connect to database.
Steps to connect to JDBC.
1) Load the driver, using Class.forName(DriverName);
2) Get the connection object, Connection con = Driver.getConnection(loaded driver name);
3) Create a SQL statement, Statement s = con.createStatement();
4) Create Resultset object using the statement created above, ResultSet rs = s.executeQuery("sql statement");
Iterate the result set to get all the values from the database.
Finally don't miss this
5) s.close();
6) con.close() ;
Example:
Steps to connect to JDBC.
1) Load the driver, using Class.forName(DriverName);
2) Get the connection object, Connection con = Driver.getConnection(loaded driver name);
3) Create a SQL statement, Statement s = con.createStatement();
4) Create Resultset object using the statement created above, ResultSet rs = s.executeQuery("sql statement");
Iterate the result set to get all the values from the database.
Finally don't miss this
5) s.close();
6) con.close() ;
Example:
import java.sql.*;
public class TestDBOracle {
public static void main(String[] args)
throws ClassNotFoundException, SQLException
{
Class.forName("oracle.jdbc.driver.OracleDriver");
//
// or
// DriverManager.registerDriver
// (new oracle.jdbc.driver.OracleDriver());
String url = "jdbc:oracle:thin:@//server.local:1521/prod";
// jdbc:oracle:thin:@//host:port/service
// or
// String url = "jdbc:oracle:thin:@server.local:1521:prodsid";
// jdbc:oracle:thin:@host:port:SID
//
// SID - System ID of the Oracle server database instance.
// By default, Oracle Database 10g Express Edition
// creates one database instance called XE.
// ex : String url = "jdbc:oracle:thin:@myhost:1521:xe";
Connection conn =
DriverManager.getConnection(url,"scott","tiger");
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
ResultSet rset =
stmt.executeQuery("select BANNER from SYS.V_$VERSION");
while (rset.next()) {
System.out.println (rset.getString(1));
}
stmt.close();
System.out.println ("Ok.");
}
}
No comments:
Post a Comment
Please Provide your feedback here