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

Asked

Viewed 2,768 times

0

I tried to make the code below but it didn’t 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();
    }
}
  • describes what exactly you mean by não deu certo

1 answer

1

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

Include the downloaded jar to your project’s Build Path.

Dynamically load the class oracle.jdbc.driver.OracleDriver before calling the getConnection() method, thus:

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

If code goes 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"));
    }
}
  • But I’m already in the main class, it was a mistake.

  • @user4873 see my Ry as it turned out

Browser other questions tagged

You are not signed in. Login or sign up in order to post.