简体   繁体   中英

Connecting Eclipse(Java) to Oracle Database

I'm trying to connect my application to my database. I does not give a error, its runs but it doesn't fetch the info. I've tried run tnsping from the command line to see if the listener is on, and it says that it's ok.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.io.*;
import javax.swing.*;

   public class Connector extends JFrame{
  public static void main(String[] args) throws SQLException, ClassNotFoundException 
 {
  Connection conn = null;
  //Statement stmt = null;
  try
  {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:dbserver", "scott","tiger");

  }
  catch(SQLException e)
  { JOptionPane.showMessageDialog(null,e.getMessage(), "Erro na COnexao!",JOptionPane.ERROR_MESSAGE);
  }
  catch(Exception e)
  { e.printStackTrace();
  }
  Statement stmt = conn.createStatement();
  ResultSet rset = stmt.executeQuery("SELECT * FROM AnimalM");
  System.out.println ("Nome Salario");
  if (rset.next()){
      System.out.println("Aloooo");
  int cod = rset.getInt(1);
  String nome = rset.getString(2);
  String nome_es = rset.getString(3);
  int id = rset.getInt(4);
  System.out.println (cod+" "+nome+" "+nome_es+" "+id);
  }
  rset.close(); //Close ResultSet
  stmt.close(); //Close Statement
   conn.close(); //Close Connection
   }
 }

It run until this instruction:

System.out.println ("Nome Salario");

And then nothing else shows, the program stops.

Does anyone have an idea of what might be happening?

I'd recommend stepping through with the debugger in Eclipse to see what's happening. Maybe the query returns no rows.

One design note: This class mixes UI, connection acquisition, and database access into one. A better approach would be do separate these into different classes. Test one feature, put it aside, and let the other classes simply use the functionality that you just implemented and proved to be working fine.

When you have one class doing too much you have no idea where the issue is when things go wrong.

You aren't closing your resources properly, either. Those should be wrapped in individual try/catch blocks.

I'd put all the code into one try/catch finally block and close the resources at the end.

I'd pass the connection into a data access object that would be responsible for acquiring the ResultSet and mapping it into objects or data structures.

I would move all Swing out of the database layer. You can reuse it without Swing that way (eg if you switch to a web UI).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM