private void uploadFlow( Connection connection, Project project, int version, Flow flow, EncodingType encType) throws ProjectManagerException, IOException { QueryRunner runner = new QueryRunner(); String json = JSONUtils.toJSON(flow.toObject()); byte[] stringData = json.getBytes("UTF-8"); byte[] data = stringData; logger.info("UTF-8 size:" + data.length); if (encType == EncodingType.GZIP) { data = GZIPUtils.gzipBytes(stringData); } logger.info("Flow upload " + flow.getId() + " is byte size " + data.length); final String INSERT_FLOW = "INSERT INTO project_flows (project_id, version, flow_id, modified_time, encoding_type, json) values (?,?,?,?,?,?)"; try { runner.update( connection, INSERT_FLOW, project.getId(), version, flow.getId(), System.currentTimeMillis(), encType.getNumVal(), data); } catch (SQLException e) { throw new ProjectManagerException("Error inserting flow " + flow.getId(), e); } }
private List<Project> fetchAllActiveProjects(Connection connection) throws ProjectManagerException { QueryRunner runner = new QueryRunner(); ProjectResultHandler handler = new ProjectResultHandler(); List<Project> projects = null; try { projects = runner.query(connection, ProjectResultHandler.SELECT_ALL_ACTIVE_PROJECTS, handler); for (Project project : projects) { List<Triple<String, Boolean, Permission>> permissions = fetchPermissionsForProject(connection, project); for (Triple<String, Boolean, Permission> entry : permissions) { if (entry.getSecond()) { project.setGroupPermission(entry.getFirst(), entry.getThird()); } else { project.setUserPermission(entry.getFirst(), entry.getThird()); } } } } catch (SQLException e) { throw new ProjectManagerException("Error retrieving all projects", e); } finally { DbUtils.closeQuietly(connection); } return projects; }
/** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public synchronized List<Usage> getUsagesForFile(String filePath, String repository) throws DatabaseAccessException { ResultSetHandler<byte[]> h = new SingleValueByteArrayHandler(); try { QueryRunner run = new QueryRunner(dataSource); byte[] result = run.query(STMT_GET_USAGES_FOR_FILE, h, filePath, repository); if (result != null) { ObjectInputStream regObjectStream = new ObjectInputStream(new ByteArrayInputStream(result)); return (List<Usage>) regObjectStream.readObject(); } else { return null; } } catch (IOException ex) { throw new DatabaseAccessException( "The content of the blob storing the usages of the file " + filePath + " repository " + repository + " could not be parsed to an Object, the database content is probably corrupt"); } catch (ClassNotFoundException ex) { throw new DatabaseAccessException( "The content of the blob storing the usages of the file " + filePath + " repository " + repository + " could not be parsed to an Object, the database content is probably corrupt"); } catch (SQLException ex) { throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex); } }
private void updateProjectSettings(Connection connection, Project project, EncodingType encType) throws ProjectManagerException { QueryRunner runner = new QueryRunner(); final String UPDATE_PROJECT_SETTINGS = "UPDATE projects SET enc_type=?, settings_blob=? WHERE id=?"; String json = JSONUtils.toJSON(project.toObject()); byte[] data = null; try { byte[] stringData = json.getBytes("UTF-8"); data = stringData; if (encType == EncodingType.GZIP) { data = GZIPUtils.gzipBytes(stringData); } logger.debug( "NumChars: " + json.length() + " UTF-8:" + stringData.length + " Gzip:" + data.length); } catch (IOException e) { throw new ProjectManagerException("Failed to encode. ", e); } try { runner.update( connection, UPDATE_PROJECT_SETTINGS, encType.getNumVal(), data, project.getId()); connection.commit(); } catch (SQLException e) { throw new ProjectManagerException( "Error updating project " + project.getName() + " version " + project.getVersion(), e); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public List<AnaMenu> anaListeGetir() throws ReadException { List<AnaMenu> liste = new ArrayList<AnaMenu>(); Connection con = null; try { con = DAOBase.instance().getConnection(); con.setAutoCommit(false); QueryRunner runner = new QueryRunner(); liste = (List<AnaMenu>) runner.query(con, Sorgular._ANAMENULIST_.qry, new BeanListHandler(AnaMenu.class)); for (AnaMenu s : liste) { s.setAltMenuler(altListeGetir(con, s.getMenuitemId())); } } catch (CreateException e) { throw new ReadException(Messages._SQL_500_.getMesaj(), null); } catch (SQLException e) { throw new ReadException(Messages._SQL_500_.getMesaj(), null); } finally { DbUtils.closeQuietly(con); } return liste == null ? new ArrayList<AnaMenu>() : liste; }
@Override public Map<String, Props> fetchProjectProperties(int projectId, int version) throws ProjectManagerException { QueryRunner runner = createQueryRunner(); ProjectPropertiesResultsHandler handler = new ProjectPropertiesResultsHandler(); try { List<Pair<String, Props>> properties = runner.query( ProjectPropertiesResultsHandler.SELECT_PROJECT_PROPERTIES, handler, projectId, version); if (properties == null || properties.isEmpty()) { return null; } HashMap<String, Props> props = new HashMap<String, Props>(); for (Pair<String, Props> pair : properties) { props.put(pair.getFirst(), pair.getSecond()); } return props; } catch (SQLException e) { throw new ProjectManagerException("Error fetching properties", e); } }
public static void main(String[] args) { conn = getConnection(); QueryRunner qr = new QueryRunner(); try { conn.setAutoCommit(false); List<Syuser> al = (List) qr.query( conn, "SELECT syuser.* FROM syuser", new BeanListHandler<Syuser>(Syuser.class)); for (Syuser u : al) { List<Syrole> rl = qr.query( conn, "SELECT syrole.* FROM syrole JOIN syuser_syrole ON syuser_syrole.SYROLE_ID = syrole.ID WHERE syuser_syrole.SYUSER_ID = ?", new BeanListHandler<Syrole>(Syrole.class), u.getId()); u.getSyroles().addAll(rl); System.out.println(u.getLoginname()); System.out.println(JSON.toJSONString(u.getSyroles())); } } catch (SQLException e) { e.printStackTrace(); try { DbUtils.rollback(conn); } catch (SQLException e1) { e1.printStackTrace(); } } finally { try { DbUtils.commitAndClose(conn); } catch (SQLException e) { e.printStackTrace(); } } }
private static List<FirmaDTO> getUpdateFirmalar() throws ReadException { QueryRunner runner = new QueryRunner(); Connection con = null; List<FirmaDTO> list = new ArrayList<FirmaDTO>(); try { con = dao.getConnection(); con.setAutoCommit(false); list = (List<FirmaDTO>) runner.query( con, "select kod, unvan, adsoyad, gsm_telefon, il, ilce, adres, durumu, tescil_no," + "uygunluk_belgesi, gecerlilik_suresi, servis_sozlesme, sozlesme_tarihi," + "tse_belge_no, eposta,monte_eden as monteEden," + "yetkili_servis as yetkiliServis," + "tse_belgesi as tseBelgesi," + "telefon_no as telefonNo," + "telefon_no_dahili as dahili," + "ce_belge_tipi as ceBelgeTipi FROM " + "akm.bakimci_firma WHERE durumu='1'", new BeanListHandler<FirmaDTO>(FirmaDTO.class)); } catch (Exception e) { throw new ReadException(e.getMessage(), null); } finally { DbUtils.closeQuietly(con); } return list; }
/** * 删除指定个Id的数据 * * @param id * @return */ public boolean deleteById(Serializable id, Class classz) { DBTableMeta dbTableMeta = DBTableMetaFactory.getDBTableMeta(classz); String sql = getSqlAnalyzer().analyzeDeleteByPrimaryKey(dbTableMeta); printSQL(sql, new Object[] {id}); QueryRunner queryRunner = new QueryRunner(); Connection conn = getDbConnectionFactory().getConnection(); try { int num = queryRunner.update(conn, sql, id); if (num == 1) { return true; } else if (num == 0) { return false; } else { throw new SQLException("数据删除异常,错误的sql与参数导致删除了" + num + "条数据"); } } catch (SQLException e) { throw new RuntimeException("删除数据失败", e); } finally { getDbConnectionFactory().releaseConnection(conn); } }
@Override public <T> T selectOneBySql(String sql, Object[] params, Class<T> classz) { QueryRunner queryRunner = new QueryRunner(); Connection conn = getDbConnectionFactory().getConnection(); printSQL(sql, params); try { if (classz.isAssignableFrom(Model.class)) { List<T> list = (List<T>) queryRunner.query(conn, sql, new AnnotationBeanListHandler(classz), params); if (list.size() > 0) { return list.get(0); } return null; } else if (baseType.contains(classz)) { return queryRunner.query(conn, sql, new ScalarHandler<T>(), params); } else { Map map = queryRunner.query(conn, sql, new MapHandler(), params); return (T) map; } } catch (SQLException e) { throw new RuntimeException(e); } finally { getDbConnectionFactory().releaseConnection(conn); } }
@Override public void add(UserIdMap userIdMap) { Connection conn = null; Object[] params = null; String sql = null; QueryRunner queryRunner = new QueryRunner(); try { conn = Conn.get(); sql = "select * from user_id_map where passengerId=? and clientId=? and channelId=?"; params = new Object[3]; params[0] = userIdMap.getPassengerId(); params[1] = userIdMap.getClientId(); params[2] = userIdMap.getChannelId(); UserIdMap oldMap = queryRunner.query(conn, sql, new BeanHandler<UserIdMap>(UserIdMap.class), params); if (oldMap == null) { sql = "insert into user_id_map(localId,passengerId,clientId,channelId) values(?,?,?,?)"; params = new Object[4]; params[0] = IdGenerator.seq(); params[1] = userIdMap.getPassengerId(); params[2] = userIdMap.getClientId(); params[3] = userIdMap.getChannelId(); queryRunner.update(conn, sql, params); } } catch (SQLException e) { logger.info(e.getMessage(), e); } }
public static void saveColumns(List<List<ContentColumn>> list) throws SQLException { QueryRunner run = new QueryRunner(); // save the url first String sql = "insert IGNORE into urls (job_id, url, success, create_time, update_time) values (1,?,1,now(),now())"; List<Object[]> paramsList = new ArrayList<Object[]>(); for (List<ContentColumn> subList : list) { for (ContentColumn column : subList) { paramsList.add(new Object[] {column.parentUrl}); } } Object[][] params = new Object[paramsList.size()][1]; for (int i = 0; i < paramsList.size(); i++) { params[i] = paramsList.get(i); } run.batch(getConnection(), sql, params); // save the columns sql = "INSERT into `columns` (job_id,url,title,value,create_by,create_time,update_by,update_time) values (job_id,?,?,?,NULL,now(),NULL,now())"; paramsList = new ArrayList<Object[]>(); for (List<ContentColumn> subList : list) { for (ContentColumn column : subList) { paramsList.add(new Object[] {column.parentUrl, column.name, column.value}); } } params = new Object[paramsList.size()][3]; for (int i = 0; i < paramsList.size(); i++) { params[i] = paramsList.get(i); } run.batch(getConnection(), sql, params); }
@Override // 在执行关注之前先判断用户是否已被关注 public void addFocusUser(long userId, long focusUserId) throws SQLException { QueryRunner queryRunner = new QueryRunner(DbTools.getDatasource()); String sql = "insert into focus(user_id,Use_user_id) values(?,?)"; Object[] param = {userId, focusUserId}; queryRunner.update(sql, param); }
public <T> T executeTop1(boolean keepConnOpen, String aTop1Query, Class<T> clazz) throws Exception { T result = null; // No DataSource so we must handle Connections manually QueryRunner run = new QueryRunner(); try { /* * Sembra che il like con i parametri ufficiali non funzioni, forse * dovuto al fatto che son tutti object */ logger.debug("Esecuzione di : " + aTop1Query); List<T> listTop1 = run.query(getConnection(), aTop1Query, getResultSetHandler(clazz)); if (listTop1.size() > 0) { logger.debug(String.format("Record Trovati: %s", listTop1.size())); result = listTop1.get(0); } } finally { // Use this helper method so we don't have to check for null if (!keepConnOpen) close(); } return result; }
/** * 查找自增主键并填充到队列中 * * @param objs 填充对象 * @throws IllegalArgumentException exception * @throws IllegalAccessException exception * @throws SQLException exception */ public void find(Object... objs) throws IllegalArgumentException, IllegalAccessException, SQLException { Class<?> clz = objs[0].getClass(); Field[] fields = clz.getDeclaredFields(); for (Field field : fields) { ORMColumn oc = field.getAnnotation(ORMColumn.class); if (oc != null && oc.physicalPkFld() && oc.autoIncrement()) { // 找到最后一个自增id QueryRunner qr = new QueryRunner(); Object identityVal = qr.query(conn, selectKey.getQuery(), new ScalarHandler<Object>()); Long identity = NumberUtils.parseNumber(identityVal.toString(), Long.class); field.setAccessible(true); // 填充到所有当中 for (int i = objs.length - 1; i >= 0; i--) { if (field.get(objs[i]) == null) { // 判null,要求主键都是包装类 // 类型转换 @SuppressWarnings("unchecked") Object val = NumberUtils.convertNumberToTargetClass(identity, ((Class<Number>) field.getType())); field.set(objs[i], val); identity--; } } break; } } }
public static UserAccount getUserAccountbyUserID(long userid) { UserAccount useraccount = null; if (SpyMemCacheClient.getInstance().IsConnected()) useraccount = (UserAccount) SpyMemCacheClient.getInstance() .get(String.format(UserAccount.key_UserAccountByUserID, userid)); if (useraccount == null) { String query = String.format(UserSQL.sqlGetUserAccountByUserID, userid); System.out.println("User Acc Query : " + query); try { ResultSetHandler<UserAccount> h = new BeanHandler<UserAccount>(UserAccount.class); Connection conn = PoolFactory.getPooling().getConnection(); QueryRunner run = new QueryRunner(); useraccount = run.query(conn, query, h); System.out.println("User Account Details : " + useraccount.toString()); conn.close(); // System.out.println(useraccount.toString()); return useraccount; } catch (SQLException e) { e.printStackTrace(); } } else { System.out.println("Mem Cache used"); } return useraccount; }
public <T> List<T> executeTrimedString(boolean keepConnOpen, String aQuery, Class<T> clazz) throws Exception { List<T> result = new ArrayList<T>(); // No DataSource so we must handle Connections manually QueryRunner run = new QueryRunner() { protected ResultSet wrap(ResultSet rs) { return StringTrimmedResultSet.wrap(rs); } }; try { /* * Sembra che il like con i parametri ufficiali non funzioni, forse * dovuto al fatto che son tutti object */ logger.debug(aQuery); result = run.query(getConnection(), aQuery, getResultSetHandler(clazz)); } finally { if (!keepConnOpen) close(); } return result; }
/** * Returns a list of saved queries * * @param criteria a multivalued map that has the filter criteria * @param start Displacement from the start of the search result * @param count Count of number of records required * @return list of saved queries * @throws LensException */ public ListResponse getList(MultivaluedMap<String, String> criteria, long start, long count) throws LensException { final StringBuilder selectQueryBuilder = new StringBuilder("select * from " + SAVED_QUERY_TABLE_NAME); final Set<String> availableFilterKeys = FILTER_KEYS.keySet(); final Sets.SetView<String> intersection = Sets.intersection(availableFilterKeys, criteria.keySet()); if (intersection.size() > 0) { final StringBuilder whereClauseBuilder = new StringBuilder(" where "); final List<String> predicates = Lists.newArrayList(); for (String colName : intersection) { predicates.add( FILTER_KEYS.get(colName).resolveFilterExpression(colName, criteria.getFirst(colName))); } Joiner.on(" and ").skipNulls().appendTo(whereClauseBuilder, predicates); selectQueryBuilder.append(whereClauseBuilder.toString()); } final String listCountQuery = "select count(*) as " + VALUE_ALIAS + " from (" + selectQueryBuilder.toString() + ") tmp_table"; selectQueryBuilder.append(" limit ").append(start).append(", ").append(count); final String listQuery = selectQueryBuilder.toString(); try { return new ListResponse( start, runner.query(listCountQuery, new SingleValuedResultHandler()), runner.query(listQuery, new SavedQueryResultSetHandler())); } catch (SQLException e) { throw new LensException("List query failed!", e); } }
/** {@inheritDoc} */ @Override public synchronized String getFilePathForTypeDeclaration( String className, String repository, List<String> asteriskImports) throws DatabaseAccessException { if (asteriskImports.isEmpty()) { return null; } ResultSetHandler<String> handler = new SingleValueStringHandler(); StringBuilder importString = new StringBuilder(); for (String currentImport : asteriskImports) { importString .append("'") .append(currentImport.substring(0, currentImport.length() - 1)) .append(className) .append("',"); } importString.deleteCharAt(importString.length() - 1); importString.append(")"); QueryRunner run = new QueryRunner(dataSource); try { return run.query( STMT_GET_FILE_PATH_FOR_TYPE_DECLARATION_WITH_PACKAGES + importString.toString(), handler, repository); } catch (SQLException ex) { throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex); } }
@Override public void cancerFocusUser(long userId, long focusUserId) throws SQLException { QueryRunner queryRunner = new QueryRunner(DbTools.getDatasource()); String sql = "delete from focus where user_id=? and Use_user_id=? "; Object[] param = {userId, focusUserId}; queryRunner.update(sql, param); }
public void insertOrUpdate(User user) throws SQLException { String sql = ""; if (select(user.getId()) != null) { sql = "update user set name=?, email=?,password=?,gender=?,role=?,age=? where id = ?"; queryRunner.update( sql, user.getIdNumber(), user.getUserName(), user.getEmail(), user.getPassword(), user.getGender(), user.getRole(), user.getAge(), user.getId()); } else { sql = "insert into user(idNumber,name,email,password,gender,role,age) values(?,?,?,?,?,?,?)"; queryRunner.update( sql, user.getIdNumber(), user.getUserName(), user.getEmail(), user.getPassword(), user.getGender(), user.getRole(), user.getAge()); } System.out.println("Insert Or Update:" + sql); }
private Project fetchProjectById(Connection connection, int id) throws ProjectManagerException { QueryRunner runner = new QueryRunner(); // Fetch the project Project project = null; ProjectResultHandler handler = new ProjectResultHandler(); try { List<Project> projects = runner.query(connection, ProjectResultHandler.SELECT_PROJECT_BY_ID, handler, id); if (projects.isEmpty()) { throw new ProjectManagerException("No active project with id " + id + " exists in db."); } project = projects.get(0); } catch (SQLException e) { logger.error(ProjectResultHandler.SELECT_PROJECT_BY_ID + " failed."); throw new ProjectManagerException("Query for existing project failed. Project " + id, e); } // Fetch the user permissions List<Triple<String, Boolean, Permission>> permissions = fetchPermissionsForProject(connection, project); for (Triple<String, Boolean, Permission> perm : permissions) { if (perm.getThird().toFlags() != 0) { if (perm.getSecond()) { project.setGroupPermission(perm.getFirst(), perm.getThird()); } else { project.setUserPermission(perm.getFirst(), perm.getThird()); } } } return project; }
@SuppressWarnings({"unchecked", "rawtypes"}) public List<MenuItemDTO> listeGetir() { List<MenuItemDTO> liste = new ArrayList<MenuItemDTO>(); Connection con = null; try { con = DAOBase.instance().getConnection(); } catch (CreateException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { con.setAutoCommit(false); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } QueryRunner runner = new QueryRunner(); try { liste = (List<MenuItemDTO>) runner.query(con, Sorgular._MENULIST_.qry, new BeanListHandler(MenuItemDTO.class)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DbUtils.closeQuietly(con); } return liste == null ? new ArrayList<MenuItemDTO>() : liste; }
/** {@inheritDoc} */ @Override public synchronized void purgeDatabaseEntries() throws DatabaseAccessException { QueryRunner run = new QueryRunner(dataSource); try { run.update(STMT_PURGE_ALL_RECORDS); } catch (SQLException ex) { throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex); } }
public List<Role> getAll() { try { QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); String sql = "select * from role"; return (List<Role>) qr.query(sql, new BeanListHandler(Role.class)); } catch (Exception e) { throw new DaoException(e); } }
@Override public int countResult(String dealNo) throws Exception { int total = 0; QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource()); String sql = "select count(*) from MONEYDATA where mon=?"; Long temp = (Long) runner.query(sql, dealNo, new ScalarHandler()); total = temp.intValue(); return total; }
/** * 删除一个用户 * * @param id */ public void deleteOne(String id) { QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "DELETE FROM user WHERE id = ?"; try { int update = queryRunner.update(sql, new Object[] {id}); } catch (SQLException e) { e.printStackTrace(); } }
/** Delete all the register older than 30 days. */ public static void fullClear() { QueryRunner run = new QueryRunner(DbConfigList.getDataSourceById("file")); try { String sql = "DELETE FROM QUEUE WHERE ADDDATE(MSG_TIME, 30) < CURDATE()"; run.update(sql); } catch (SQLException e) { log.fatal("unable to clear queue", e); } }
/** {@inheritDoc} */ @Override public synchronized void deleteRepository(String repoName) throws DatabaseAccessException { QueryRunner run = new QueryRunner(dataSource); try { run.update(STMT_DELETE_REPOSITORY, repoName); } catch (SQLException ex) { throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex); } }
/** 부분 커밋하면서 입력한다. ex) batchInsert(dataSource,"QQ", params, 1000); */ public static void batchInsert( DataSource dataSource, String tableName, List<Object[]> params, int commitInterval) { Connection conn = null; try { conn = dataSource.getConnection(); conn.setAutoCommit(false); QueryRunner runner = new QueryRunner(); StringAppender appender = new StringAppender(); appender.appendLine( "SELECT a.TABLE_NAME,a.COLUMN_NAME,COMMENTS,DATA_TYPE,DATA_LENGTH,DATA_PRECISION,DATA_SCALE"); appender.appendLine("FROM user_tab_columns a JOIN USER_COL_COMMENTS b"); appender.appendLine("ON a.COLUMN_NAME = b.COLUMN_NAME AND a.TABLE_NAME = b.TABLE_NAME"); appender.appendLine("WHERE a.TABLE_NAME = ? "); appender.appendLine("ORDER BY a.TABLE_NAME, COLUMN_ID "); List<String> columnNames = Lists.newArrayList(); // 걍 한번 쓸거라 일케 함 List<Map<String, Object>> result = runner.query(conn, appender.toString(), LIST_MAP_HANDLER, tableName); for (Map<String, Object> value : result) { columnNames.add(value.get("COLUMN_NAME").toString()); } String sql = "INSERT INTO " + tableName + " (" + StringUtil.join(columnNames, ",") + ") values (" + StringUtil.iterateStr("?", ",", columnNames.size()) + ")"; List<List<Object[]>> splited = CollectionUtil.splitBySize(params, commitInterval); for (List<Object[]> inputList : splited) { Object[][] convertedList = new Object[inputList.size()][]; for (int i = 0; i < convertedList.length; i++) { Object[] input = inputList.get(i); Object[] converted = new Object[input.length]; for (int j = 0; j < input.length; j++) { converted[j] = CONVERTER.convert(input[j]); } convertedList[i] = converted; } runner.batch(conn, sql, convertedList); conn.commit(); } } catch (SQLException e) { throw new SQLRuntimeException(e); } finally { DbUtils.closeQuietly(conn); } }