reademployeerecords.java

来自「java 完全探索的随书源码」· Java 代码 · 共 94 行

JAVA
94
字号
import java.sql.*;public class ReadEmployeeRecords{  // Private reference to an instance of the Connection  private Connection conn = null;  // Default Constructor  public ReadEmployeeRecords( Connection connection )  {    conn = connection;  }  // Public method to read all of the records for the employees  public void readRecords()  {    // SQL Statement to get all of the employees    String READ_EMPLOYEE_SQL_STMT = "SELECT * FROM EMP";    Statement stmt = null;    ResultSet rs = null;    try    {      stmt = getConnection().createStatement();      stmt.execute( READ_EMPLOYEE_SQL_STMT );      rs = stmt.getResultSet();    }    catch( SQLException ex )    {      ex.printStackTrace();    }    // Call the public method to print the employees out    printEmployeeRecords( rs );  }  // Private accessor for the connection  private Connection getConnection()  {    return conn;  }  // Use the ResultSet and print the records to the console  public void printEmployeeRecords( ResultSet rs )  {    try    {      // While there are more records to read from the ResultSet      while( rs.next() )      {        // Get the data by using the column index from the table.        // Could also have used the column names like        // rs.getString( "firstName" );        //        String nbr = rs.getString( 1 );        String name = rs.getString( 2 );        String job = rs.getString( 3 );        String mgr = rs.getString( 4 );        Timestamp hireDate = rs.getTimestamp(5);        Employee employee = new Employee( nbr, name, job, mgr, hireDate );        System.out.println( employee.toString() );      }    }    catch( SQLException ex )    {      ex.printStackTrace();    }  }  // Method to start this class and test the examples  public static void main(String[] args)  {    // Use the previous DatabaseManager    Connection conn = DatabaseManager.getConnection();    ReadEmployeeRecords reader = new ReadEmployeeRecords( conn );    reader.readRecords();    // Always make sure to close the connection when you are finished    try    {      conn.close();    }    catch( SQLException ex )    {      ex.printStackTrace();    }    catch( Exception ex )    {      ex.printStackTrace();    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?