Tuesday, February 4, 2014

Oracle JDBC connection in java under Netbeans

1. Create your project:

2. Project name: jdbcProject
3.Downoad the oracle jar ojdbc14.jar from here or here

4. Add the jar to your project:
   - by right clicking your oracle project
   -Click on Properties
   -Under Categories at the left Select Libraries
   -Click on Add Jar/Folder button at the right
   -Go to the jar location , select it and Open, OK, OK

5. Create a table in your oracle database:
create table student (name varchar(20), country varchar(20));
6. Write code
imports:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

 Your Code:

public class JdbcProject {

    
    public static void main(String[] args) {
       
        try {  
          String sid="orcl";  //your oracle sid
          String username="user"; 
          String password= "pass";  
          DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());  
          Connection connection = DriverManager.getConnection(  
                "jdbc:oracle:thin:@localhost:1521:"+sid, username, password);  

        //Statement statement = connection.createStatement();  
           
          String name="soulemane";
          String country="cameroon";
          String query = " insert into student(name,country)values(?,?)";
          PreparedStatement preparedStmt = connection.prepareStatement(query);
           //System.out.println("Data is inserted:");
           preparedStmt.setString(1, name);
           preparedStmt.setString(2,country);

            // execute the preparedstatement
           preparedStmt.execute();
           connection.close(); 
          } catch (Exception e) {  
            e.printStackTrace();  
          }  
           System.out.println("Data is inserted:");
    }
}
  
 7. Final RUN your project and have fun

No comments:

Post a Comment