1. Introduction of result set
When we query the database, we return a two-dimensional result set, and we need to use resultset to traverse the result set to get the data for each row.
2. Use result to traverse query results
Boolean next (): Moves the cursor forward one line from the current position.
String getString (int columnindex): Gets the value of the specified column in the current row of this ResultSet object as a string in the Java programming language.
String getString (int ColumnLabel): Gets the value of the specified column in the current row of this ResultSet object as a string in the Java programming language.
Example:
Public classJDBCDemo8 {Private StaticMysqlutil Dbutil =NewMysqlutil (); /*** Traverse Query Results *@throwsException*/ Private Static voidListemp ()throwsexception{Connection Conn=dbutil.getconnection (); String SQL= "SELECT * from EMP2"; PreparedStatement pstmt=conn.preparestatement (SQL); ResultSet RS= Pstmt.executequery ();//returns a resultset result set while(Rs.next ()) {//String getString (int columnindex) intid = rs.getint (1);//Gets the value ID of the first columnString name = rs.getstring (2); //String getString (int columnlabel) This is good.Double salary = rs.getdouble ("Salary"); intAge = Rs.getint ("Age"); System.out.println ("Employee ID:" +id+ ", Name:" +name+ ", Salary:" +salary+ ", Age:" +Age ); System.out.println ("================="); } } Private StaticList<emp> LISTEMP2 ()throwsexception{List<Emp> emplist =NewArraylist<emp>(); Connection Conn=dbutil.getconnection (); String SQL= "SELECT * from EMP2"; PreparedStatement pstmt=conn.preparestatement (SQL); ResultSet RS=Pstmt.executequery (); while(Rs.next ()) {intid = rs.getint (1); String name= Rs.getstring (2); Double Salary= Rs.getdouble ("Salary"); intAge = Rs.getint ("Age"); EMP EMP=NewEmp (id,name,salary,age); Emplist.add (EMP); } returnemplist; } Public Static voidMain (string[] args)throwsexception{listemp (); List<Emp> emplist =LISTEMP2 (); for(emp emp:emplist) {System.out.println (EMP); } }}
JDBC (4)-result result set