How do I connect a program in java with oracle 10g?

0

I've tried the code below but it did not work, I'm using Oracle 10g.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class AcessoBanco {

    public static void main(String[] args) throws Exception{
        String sql = "select id_usuario, nome_razao from usuario";
        String url = "jdbc:oracle:thin:@localhost:1521:xe";

        try(
        Connection con = DriverManager.getConnection(url, "david", "5550123");
        PreparedStatement stm = con.prepareStatement(sql);
        ResultSet rs = stm.executeQuery()){
            while(rs.next()){
                System.out.println(rs.getString("nome_razao"));
            }
        }
//      rs.close();
//      stm.close();
//      con.close();
    }
}
    
asked by anonymous 11.06.2014 / 03:17

1 answer

1

You should download the JDBC driver at the following link: Oracle Database 10g Release 2 JDBC Drivers .

Add the downloaded jar to your project's Build Path.

Make your code dynamically load the oracle.jdbc.driver.OracleDriver class before calling the getConnection () method, like this:

Class.forName("oracle.jdbc.driver.OracleDriver");

If code will look like this:

try(Class.forName("oracle.jdbc.driver.OracleDriver"); //repare nessa linha
        Connection con = DriverManager.getConnection(url, "david", "5550123");
        PreparedStatement stm = con.prepareStatement(sql);
        ResultSet rs = stm.executeQuery()){
    while(rs.next()){
        System.out.println(rs.getString("nome_razao"));
    }
}
    
11.06.2014 / 03:21