Skip to main content

This blog explains how to connect to the Oracle10g database in Java.
(u can use netbeans as well then no need of classpath)

Connect To Oracle10g database In Java
There are 5 steps to create a connection with an Oracle10g database in Java.
  1. First register the driver class
  2. Create the connection
  3. Create a statement
  4. Execute queries
  5. Close the connection
1. First, register the driver class
The class.forName() method of the class registers the driver class. 

Syntax
public static void forName(String classname) throws ClassNotFoundException
Example
Class.forName("oracle.jdbc.driver.OracleDriver");

2. Create the connection object
The getConnection() method of the DriverManager class establishes the connection with the Oracle database.
Syntax
public static Connection getConnection(String url) throws Exception
public static Connection getConnetion(String name, String url, String password)

Example
Connection connection=DriverManager.getConnection("jdbc.oracle.thin:@localhost:xe","system","password");
Instead of localhost we provide our system name there.
Explanation:
Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe where
 jdbc is the API,
 oracle is the database,
 thin is the driver, 
localhost is the server name on which oracle is running, 
we may also use IP address, 
1521 is the port number
 and
 XE is the Oracle service name. 

3. Create the Statement object
The createStatement() method of the Connection interface is used to create the statement. This object is responsible for executing queries with the Oracle database.
Syntax
public Statement createStatement() throws Exception
Example
Statement statement=connection.cretaeStatement();
4. Execute the Queries
This method of the Statement interface executes the queries to the Oracle database. This method returns the object of ResultSet that can be used to get all the records of a table.
Syntax
public ResultSet executeQuery(String s) throws Exception
Example
ResultSet resultset=statement.executeQuery("Select 8 from emp");
while(resultset.next());
{
System.out.println(resultset.getInt(1)+ "" + resultset.getString(2));
}

5. Close the connection object
By closing the connection object the statement and ResultSet will be closed automatically. The close() method of the Connection interface closes the connection.
Syntax
public void close() throws Exception
Example
connection.close();
Now, take an example that shows a connection with Oracle10g database
For making a Java application with the Oracle database, we need to use the above 5 steps to perform database connectivity. In this example, we are using Oracle10g as the database. So we need to know the following information for the Oracle database.
Driver class
         For Oracle; the driver class is in oracle.jdbc.driver.OracleDriver.

Connection URL
         For Oracle10g the URL is "jdbc:oracle:thin:@localhost:1521:xe" (instead of localhost we provide our system name also) where jdbc is the API, Oracle is the database, thin is the driver, localhost is the server name on which Oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. We may get all that information from the tnsnames.ora file.

username
         The default username for the Oracle database is SYSTEM.

Password
         This is user define given at the time of installing the Oracle database.

Now, start creating a connection with the Oracle10g database.
Create a table
Now open the Run SQL command line and write the following:
create table student(s_id number(5), s_name varchar2(35),s_age number(3));
Our table is created, now insert some data into it.
insert into student values(10,'Sandeep',22);
insert into student values(11,'Rahul',20);

Now we have inserted two rows into the student table that we have to display using Java.
To connect a Java application with the Oracle database we need the ojdbc14.jar file.
There are two ways to load this jar file
  1. paste the jar ojdbc14.jar in C:\Program Files\Java\jre7\lib\ext folder.
  2. set classpath for this jar file.
1. Paste the file
First search the ojdbc14.jar file (Like C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib contains this file) then goto JRE/lib/ext folder and paste the ojdbc14.jar file in it.
2. Set the classpath
Go to environment variable then click on the new tab. In the variable name write the classpath and in the variable value paste the path to the ojdbc14.jar (like C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;)
See the following image:
Fig-1.jpg
Display the student record The following example Java file displays the student record.
Example
OracleConnectionEx.java
This example fetches all the records of the student table.
import java.sql.*;
class OracleConnectionEx
  {
    public static void main(String args[]) throws Exception
      {
        try
          {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection connection=DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:xe","system","sandeep");
            Statement statement=connection.createStatement();
            ResultSet resultset=statement.executeQuery("select * from student");
            while(resultset.next())
              {
                System.out.println(resultset.getInt("S_ID")+"  "+resultset.getString("S_NAME")+"  "+resultset.getInt("S_AGE"));
              }
            connection.close();
          }
        catch(Exception ex)
          {
            System.out.println(ex);
          }
      }
  } Output
Fig-2.jpg

thank you........................

Comments

Popular posts from this blog

Naming Convention

  Naming Convention : A naming convention is  a convention for naming things: Please find below the table for naming conventions: Naming Convention Format Example Camel Case camelCase 🐪aBcD Kebab Case kebab-case 🍢a-b-c-d Snake Case snake_case 🐍a_b_c_d Pascal Case PascalCase 🧑‍🦳AbCd Flat Case flatcase 📏abcd Upper Flat Case UPPERFLATCASE ABCD Screaming Snake Case SCREAMING_SNAKE_CASE 🐍A_B_C_D Camel Snake Case camel_Snake_Case 🐪🐍ab_Cd Pascal Snake Case Pascal_Snake_Case Ab_Cd Train Case Train-Case 🚃Ab-Cd Cobol Case COBOL-CASE 🍢AB-CD
How to run lex yacc programs on win 10 In short: For Lex steps to run: lex lex7.l gcc lex.yy.c a     For YACC steps to run: lex simple_compound.l yacc -d simple_compound.y gcc lex.yy.c y.tab.c a                          A.Lex 1. download flex for windows http://flex-windows-lex-and-yacc.software.informer.com/2.5/ 2. install it locatin:  C:\Flex Windows\ 3.open cmd 4.You need to change location as follows:  cd C:\Flex Windows\EditPlusPortable 5. Steps to run : lex lex7.l gcc lex.yy.c a Output : Word Count : 13 Char Count : 80 Line Count : 7 codes : lex7.l %{ /* *Program to count no of characters, words and lines */ #include<stdio.h> #include<string.h> int c=0,w=0,l=0; %} %% [\t ]+              /* ignore whitespace */ [a-zA-z]+             {w=w+1; c=c+ yyleng;} [\n ]                           {l=l+1;} ['{','}''(',')',.,",;]          {c=c+1;} %% int main() {     yyin= fopen("file1.txt&qu

Add items in shopping cart using ArrayList

 Add items in shopping cart: We are using ArrayList Code: import java.util.*; public class Main {  public static void main (String[]args)   {     ArrayList < String > items = new ArrayList < String > ();     Scanner sc = new Scanner (System.in);       items.add ("folder");       items.add ("flower");       items.add ("Car");       items.add ("Bottle");       items.add ("Mask");       items.add ("Box");       System.out.println ("Shopping card items");       System.out.print (items);       System.out.println ("Enter item which you want:");       String rmv = sc.nextLine ();       items.remove (rmv);       System.out.println ("Shopping card items");       System.out.print (items);   } } Output: Shopping card items                                                                                                              [folder, flower, Car, Bottle, Mask, Box]Enter item which you want: