How to retrieve data using JDBC

2019-09-04 23:31发布

问题:

I have been trying with the following code.

The connection is being made. But the resultSet is coming as empty (not null), whereas there are a couple of entries (2 fields each) in the database for the same.

It does not enter the while condition. I'm new to JDBC, please help!

My code is:

import java.sql.*;

public class JDBCTest123
{

    public static void main(String[] args)
    {
        System.out.println("oracle Connect Example.");
        Connection conn = null;
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
        String driver = "oracle.jdbc.driver.OracleDriver";
        String userName = "system";
        String password = "mumpymamai";
        Statement stmt = null;
        String query = "select * from table1";  
        try
        {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);
            stmt = conn.createStatement();
            System.out.println("Connected to the database");
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next())
            {
                System.out.println(rs.getString(1));
                System.out.println(rs.getString(2));
            }
            conn.close();
            System.out.println("Disconnected from database");
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

And the output is:

oracle Connect Example.
Connected to the database
Disconnected from database

回答1:

So few suggestions. I recommend to you use PreparedStatements which are more faster and safer.

PreparedStatement ps = null;
conn = DriverManager.getConnection(url, userName, password);
ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
   // do some work
}

Second suggestion, call close() method in finally block, because application may crash and then your connection won't be closed. Finally block guarantees that will be always called.


Third suggestion if it doesn't work without Exception, probably you have empty table.