Guest User

Untitled

a guest
Mar 17th, 2017
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.72 KB | None | 0 0
  1. package com.myapp.jdbc;
  2.  
  3. import java.sql.ResultSetMetaData;
  4. import java.sql.SQLException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import javax.sql.rowset.JdbcRowSet;
  9.  
  10. import com.myapp.generics.Customer;
  11. import com.sun.rowset.JdbcRowSetImpl;
  12.  
  13. public class TestJdbcRowSet {
  14.    
  15.     JdbcRowSet rowset=null;
  16.    
  17.     public TestJdbcRowSet() {
  18.     rowset=new JdbcRowSetImpl();
  19.     try {
  20.         rowset.setUrl("jdbc:mysql://localhost:3306/citrix");
  21.         rowset.setUsername("admin");
  22.         rowset.setPassword("admin");
  23.         rowset.setCommand("select * from customer");
  24.         rowset.execute();
  25.     } catch (SQLException e) {
  26.    
  27.         e.printStackTrace();
  28.     }  
  29.        
  30.     }
  31.     public List<Customer> showCustomers(){
  32.        
  33.         try{
  34.             ResultSetMetaData metadata=rowset.getMetaData();
  35.             int noOfCols=metadata.getColumnCount();
  36.             List<Customer> list=new ArrayList<>();
  37.         while(rowset.next()){
  38.             //for(int i=1;i<=noOfCols;i++){
  39.                
  40.                 list.add(new Customer(
  41.                         rowset.getInt(1),
  42.     rowset.getString(2),rowset.getInt(3)));
  43.                
  44.             //}
  45.         }
  46.         return list;
  47.         }catch(SQLException e){
  48.             e.printStackTrace();
  49.         }
  50.         return null;       
  51.     }
  52.    
  53.     public void addCustomer(Customer customer){
  54.        
  55.        
  56.         try {
  57.             rowset.moveToInsertRow();
  58.             rowset.updateInt(1,customer.getId());
  59.             rowset.updateString(2,customer.getName());
  60.             rowset.updateInt(3,customer.getAge());
  61.             rowset.insertRow();
  62.             rowset.beforeFirst();
  63.            
  64.         } catch (SQLException e) {
  65.             // TODO Auto-generated catch block
  66.             e.printStackTrace();
  67.         }
  68.        
  69.     }
  70.  
  71.     public static void main(String[] args) {
  72.         TestJdbcRowSet rowset=new TestJdbcRowSet();
  73.         rowset.addCustomer(new Customer(4,"SomeName4",100));
  74.         List<Customer> list=rowset.showCustomers();
  75.        
  76.         list.forEach(c->System.out.println(c));
  77.  
  78.     }
  79.  
  80. }
Add Comment
Please, Sign In to add comment