1 43 package net.jforum.dao.generic; 44 45 import java.sql.Connection ; 46 import java.sql.PreparedStatement ; 47 import java.sql.ResultSet ; 48 import java.sql.SQLException ; 49 import java.sql.Statement ; 50 51 import net.jforum.JForumExecutionContext; 52 import net.jforum.util.preferences.ConfigKeys; 53 import net.jforum.util.preferences.SystemGlobals; 54 55 59 public class AutoKeys 60 { 61 private static boolean supportAutoGeneratedKeys = SystemGlobals.getBoolValue(ConfigKeys.DATABASE_AUTO_KEYS); 62 private String autoGeneratedKeysQuery; 63 64 protected boolean supportAutoGeneratedKeys() 65 { 66 return supportAutoGeneratedKeys; 67 } 68 69 74 protected void setAutoGeneratedKeysQuery(String query) 75 { 76 this.autoGeneratedKeysQuery = query; 77 } 78 79 protected String getAutoGeneratedKeysQuery() 80 { 81 return this.autoGeneratedKeysQuery; 82 } 83 84 protected String getErrorMessage() 85 { 86 return "Could not obtain the latest generated key. This error may be associated" 87 +" to some invalid database driver operation or server failure." 88 +" Please check the database configurations and code logic."; 89 } 90 91 protected PreparedStatement getStatementForAutoKeys(String queryName, Connection conn) throws SQLException 92 { 93 PreparedStatement p = null; 94 if (this.supportAutoGeneratedKeys()) { 95 p = conn.prepareStatement(SystemGlobals.getSql(queryName), 96 Statement.RETURN_GENERATED_KEYS); 97 } 98 else { 99 p = conn.prepareStatement(SystemGlobals.getSql(queryName)); 100 } 101 102 return p; 103 } 104 105 protected PreparedStatement getStatementForAutoKeys(String queryName) throws SQLException 106 { 107 return this.getStatementForAutoKeys(queryName, JForumExecutionContext.getConnection()); 108 } 109 110 protected int executeAutoKeysQuery(PreparedStatement p) throws SQLException 111 { 112 return this.executeAutoKeysQuery(p, JForumExecutionContext.getConnection()); 113 } 114 115 protected int executeAutoKeysQuery(PreparedStatement p, Connection conn) throws SQLException 116 { 117 int id = -1; 118 p.executeUpdate(); 119 120 if (this.supportAutoGeneratedKeys()) { 121 ResultSet rs = p.getGeneratedKeys(); 122 if (rs.next()) { 123 id = rs.getInt(1); 124 } 125 rs.close(); 126 } 127 else { 128 p = conn.prepareStatement(this.getAutoGeneratedKeysQuery()); 129 ResultSet rs = p.executeQuery(); 130 131 if (rs.next()) { 132 id = rs.getInt(1); 133 } 134 135 rs.close(); 136 } 137 138 boolean valid = true; 139 if (id == -1) { 140 valid = false; 141 } 142 143 if (!valid) { 144 throw new SQLException (this.getErrorMessage()); 145 } 146 147 return id; 148 } 149 } 150 | Popular Tags |