Add tutorial files for ResultSet2JSON Article (#11912)

* Add tutorial files

* Move script to new folder

* Use Maven/H2 instead of JBang/DuckDB

* Use Java 8

* Usen an older versio of JOOQ

* Format according to Beldung Intellij guide

* Remove dangling commit

* Use 2-space indentation

* Apply formatting from Eclipse

* Add unit test

* Add assertion

* Change test names

* Change method names

Co-authored-by: root <root@localhost.localdomain>
Co-authored-by: Alireza Ghasemi <alireza.ghasemi1@swisscom.com>
This commit is contained in:
Alireza Ghasemi 2022-05-16 17:34:55 +02:00 committed by GitHub
parent b3a7e039f1
commit 365f029e3a
4 changed files with 231 additions and 3 deletions

View File

@ -0,0 +1,4 @@
Username,Id,First name,Last name
doe1,7173,John,Doe
smith3,3722,Dana,Smith
john22,5490,John,Wang
1 Username Id First name Last name
2 doe1 7173 John Doe
3 smith3 3722 Dana Smith
4 john22 5490 John Wang

View File

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.core-java-persistence-2</groupId>
<artifactId>core-java-persistence-2</artifactId>
@ -41,6 +39,20 @@
<artifactId>mssql-jdbc</artifactId>
<version>${mssql.driver.version}</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.11.11</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220320</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,137 @@
package com.baeldung.resultset2json;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.impl.DSL;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
public class ResultSet2JSON {
public static void main(String... args) throws ClassNotFoundException, SQLException {
ResultSet2JSON testClass = new ResultSet2JSON();
testClass.convertWithoutJOOQ();
}
public void convertWithoutJOOQ() throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONArray result1 = resultSet2JdbcWithoutJOOQ(resultSet);
System.out.println(result1);
resultSet.close();
}
public void convertUsingJOOQDefaultApproach() throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONObject result1 = resultSet2JdbcUsingJOOQDefaultApproach(resultSet, dbConnection);
System.out.println(result1);
resultSet.close();
}
public void convertUsingCustomisedJOOQ() throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONArray result1 = resultSet2JdbcUsingCustomisedJOOQ(resultSet, dbConnection);
System.out.println(result1);
resultSet.close();
}
public static JSONArray resultSet2JdbcWithoutJOOQ(ResultSet resultSet) throws SQLException {
ResultSetMetaData md = resultSet.getMetaData();
int numCols = md.getColumnCount();
List<String> colNames = IntStream.range(0, numCols)
.mapToObj(i -> {
try {
return md.getColumnName(i + 1);
} catch (SQLException e) {
e.printStackTrace();
return "?";
}
})
.collect(Collectors.toList());
JSONArray result = new JSONArray();
while (resultSet.next()) {
JSONObject row = new JSONObject();
colNames.forEach(cn -> {
try {
row.put(cn, resultSet.getObject(cn));
} catch (JSONException | SQLException e) {
e.printStackTrace();
}
});
result.put(row);
}
return result;
}
public static JSONObject resultSet2JdbcUsingJOOQDefaultApproach(ResultSet resultSet, Connection dbConnection) throws SQLException {
JSONObject result = new JSONObject(DSL.using(dbConnection)
.fetch(resultSet)
.formatJSON());
return result;
}
public static JSONArray resultSet2JdbcUsingCustomisedJOOQ(ResultSet resultSet, Connection dbConnection) throws SQLException {
ResultSetMetaData md = resultSet.getMetaData();
int numCols = md.getColumnCount();
List<String> colNames = IntStream.range(0, numCols)
.mapToObj(i -> {
try {
return md.getColumnName(i + 1);
} catch (SQLException e) {
e.printStackTrace();
return "?";
}
})
.collect(Collectors.toList());
List<JSONObject> json = DSL.using(dbConnection)
.fetch(resultSet)
.map(new RecordMapper<Record, JSONObject>() {
@Override
public JSONObject map(Record r) {
JSONObject obj = new JSONObject();
colNames.forEach(cn -> obj.put(cn, r.get(cn)));
return obj;
}
});
return new JSONArray(json);
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.resultset2json;
import static com.baeldung.resultset2json.ResultSet2JSON.resultSet2JdbcWithoutJOOQ;
import static com.baeldung.resultset2json.ResultSet2JSON.resultSet2JdbcUsingJOOQDefaultApproach;
import static com.baeldung.resultset2json.ResultSet2JSON.resultSet2JdbcUsingCustomisedJOOQ;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ResultSet2JSONUnitTest {
JSONObject object = new JSONObject(
"{\"records\":[[\"doe1\",\"7173\",\"John\",\"Doe\"],[\"smith3\",\"3722\",\"Dana\",\"Smith\"],[\"john22\",\"5490\",\"John\",\"Wang\"]],\"fields\":[{\"schema\":\"PUBLIC\",\"name\":\"USERNAME\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"},{\"schema\":\"PUBLIC\",\"name\":\"ID\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"},{\"schema\":\"PUBLIC\",\"name\":\"First name\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"},{\"schema\":\"PUBLIC\",\"name\":\"Last name\",\"type\":\"VARCHAR\",\"table\":\"WORDS\"}]}");
JSONArray array = new JSONArray(
"[{\"USERNAME\":\"doe1\",\"First name\":\"John\",\"ID\":\"7173\",\"Last name\":\"Doe\"},{\"USERNAME\":\"smith3\",\"First name\":\"Dana\",\"ID\":\"3722\",\"Last name\":\"Smith\"},{\"USERNAME\":\"john22\",\"First name\":\"John\",\"ID\":\"5490\",\"Last name\":\"Wang\"}]");
@Test
void whenResultSetConvertedWithoutJOOQ_shouldMatchJSON() throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc1", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONArray result1 = resultSet2JdbcWithoutJOOQ(resultSet);
resultSet.close();
assertTrue(array.similar(result1));
}
@Test
void whenResultSetConvertedUsingJOOQDefaultApproach_shouldMatchJSON() throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc2", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONObject result2 = resultSet2JdbcUsingJOOQDefaultApproach(resultSet, dbConnection);
resultSet.close();
assertTrue(object.similar(result2));
}
@Test
void whenResultSetConvertedUsingCustomisedJOOQ_shouldMatchJSON() throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc3", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONArray result3 = resultSet2JdbcUsingCustomisedJOOQ(resultSet, dbConnection);
resultSet.close();
assertTrue(array.similar(result3));
}
}