Skip to content

Commit

Permalink
Merge pull request #25 from nhnb/query_as_map
Browse files Browse the repository at this point in the history
added new method queryAsMap
  • Loading branch information
nhnb authored Jun 8, 2023
2 parents 1a09a50 + 757aa63 commit 91754ae
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/marauroa/server/db/DBTransaction.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/***************************************************************************
* (C) Copyright 2003-2011 - Marauroa *
* (C) Copyright 2003-2023 - Marauroa *
***************************************************************************
***************************************************************************
* *
Expand All @@ -17,6 +17,7 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

Expand Down Expand Up @@ -59,6 +60,8 @@ protected void setThread(Thread thread) {
/**
* prints an error if a DBTransaction is accessed outside the thread
* it was bound to.
*
* @param acceptUnused do no report accessing an available DBTransaction
*/
private void ensureCorrectThread(boolean acceptUnused) {
if (thread == null) {
Expand Down Expand Up @@ -202,6 +205,26 @@ public ResultSet query(String query, Map<String, Object> params) throws SQLExcep
return databaseAdapter.query(sql);
}

/**
* queries the database and returns map with one entry per row.
*
* @param query SQL statement
* @param params parameter values
* @return ResultSet
* @throws SQLException in case of an database error
*/
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> queryAsMap(String query, Map<String, Object> params) throws SQLException {
ensureCorrectThread(false);
String sql = subst(query, params);
ResultSet resultSet = databaseAdapter.query(sql);
Map<K, V> res = new HashMap<K, V>();
while (resultSet.next()) {
res.put((K) resultSet.getObject(1), (V) resultSet.getObject(2));
}
return res;
}

/**
* queries the database and returns the first column in the first row as integer (for example for a count(*)).
*
Expand Down

0 comments on commit 91754ae

Please sign in to comment.