1 19 20 package org.polepos.teams.jdbc; 21 22 23 24 import java.sql.ResultSet ; 25 import java.sql.SQLException ; 26 27 import org.polepos.circuits.sepang.*; 28 import org.polepos.framework.*; 29 30 33 public class SepangJdbc extends JdbcDriver implements SepangDriver{ 34 35 Tree lastRead; 36 37 public void takeSeatIn(Car car, TurnSetup setup) throws CarMotorFailureException{ 38 39 super.takeSeatIn(car, setup); 40 41 jdbcCar().openConnection(); 43 44 jdbcCar().dropTable( "malaysia" ); 48 jdbcCar().createTable( "malaysia", new String []{ "id", "preceding", "subsequent", "name", "depth" }, new Class []{Integer.TYPE,Integer.TYPE,Integer.TYPE,String .class, Integer.TYPE} ); 49 50 jdbcCar().closeConnection(); 51 } 52 53 public void write(){ 54 55 Tree tree = Tree.createTree(setup().getTreeDepth()); 56 Tree.traverse(tree, new TreeVisitor() { 57 public void visit(Tree tree) { 58 StringBuffer s = new StringBuffer ( "insert into malaysia (id, preceding, subsequent, name, depth ) values (" ); 59 s.append(tree.id); 60 s.append(","); 61 if(tree.preceding != null){ 62 s.append(tree.preceding.id); 63 }else{ 64 s.append(0); 65 } 66 s.append(","); 67 if(tree.subsequent != null){ 68 s.append(tree.subsequent.id); 69 }else{ 70 s.append(0); 71 } 72 s.append(", '"); 73 s.append(tree.name); 74 s.append("', "); 75 s.append(tree.depth); 76 s.append(")"); 77 jdbcCar().executeSQL(s.toString()); 78 } 79 }); 80 jdbcCar().commit(); 81 } 82 83 84 public void read(){ 85 try { 86 lastRead = read(1); 87 Tree.traverse(lastRead, new TreeVisitor() { 88 public void visit(Tree tree) { 89 addToCheckSum(tree.getDepth()); 90 } 91 }); 92 } catch (SQLException e) { 93 e.printStackTrace(); 94 } 95 } 96 97 private Tree read(int id) throws SQLException { 98 99 ResultSet rs = jdbcCar().executeQuery("select * from malaysia where id=" + id); 100 rs.next(); 101 102 Tree tree = new Tree(rs.getInt(1),rs.getString(4), rs.getInt(5)); 103 int precedingID = rs.getInt(2); 104 int subsequentID = rs.getInt(3); 105 rs.close(); 106 if(precedingID > 0){ 107 tree.preceding = read(precedingID); 108 } 109 if(subsequentID > 0){ 110 tree.subsequent = read(subsequentID); 111 } 112 return tree; 113 } 114 115 public void read_hot() { 116 read(); 117 } 118 119 public void delete(){ 120 try{ 121 delete(1); 122 jdbcCar().commit(); 123 }catch ( SQLException sqlex ){ 124 sqlex.printStackTrace(); 125 } 126 } 127 128 private void delete(int id) throws SQLException { 129 ResultSet rs = jdbcCar().executeQuery("select * from malaysia where id=" + id); 130 rs.next(); 131 int precedingID = rs.getInt(2); 132 int subsequentID = rs.getInt(3); 133 rs.close(); 134 if(precedingID > 0){ 135 delete(precedingID); 136 } 137 if(subsequentID > 0){ 138 delete(subsequentID); 139 } 140 jdbcCar().executeUpdate("delete from malaysia where id=" + id); 141 } 142 143 } 144 | Popular Tags |