从Oracle数据库表中读取数据,并使用Java将数据写入文件。

huangapple go评论80阅读模式
英文:

Reading data from oracle database table and writing to file using java

问题

我正在使用JDBC从数据库中读取数据。数据如下。

从Oracle数据库表中读取数据,并使用Java将数据写入文件。

我需要将此数据插入到一个使用Post API的应用程序中。为此,我需要将数据按照API接受的格式写入文件中。

所以我将以以下格式创建OrgName.json文件。

{
    "delete": [
        {
            "canonicalName": "TCS"
        }
    ],
    "update": [
        {
            "canonicalName": "Wipro tech",
            "synonyms": [
                "Wipro technology"
            ]
        },
        {
            "canonicalName": "Infosys",
            "synonyms": [
                "Infosys tech"
            ]
        }
    ],
    "add": [
        {
            "canonicalName": "Apple Computers",
            "synonyms": [
                "Apple"
            ]
        },
        {
            "canonicalName": "Google India",
            "synonyms": ["Google"]
        }
    ]
}

因此,将会有3个分组。所有update的值将出现在update标签中,基于OPERATION列的add值将出现在add标签中,delete值将出现在delete标签中。columnORGNAME值将成为文件中的canonicalName名称。如果synonymsnull,则不会出现,否则将会出现。

我了解Java中的JDBC。我可以使用PreparedstatementexecuteQuery来读取数据,并可以使用sysout在控制台中显示。但是我不能按照上述格式将数据写入文件中。

有人可以帮帮我吗?我是数据库开发人员,所以无法思考如何做到这一点。即使是最小的帮助对我来说也会很多。

我想将Resultset转换为上述文件,但我做不到。

英文:

I am reading data from database using JDBC. data is like below.

从Oracle数据库表中读取数据,并使用Java将数据写入文件。

I have to insert this data into an application using Post API. for that I need to write data into file in the format API accepts.

so I will create OrgName.json file in the below format.

{
    "delete": [
        {
            "canonicalName": "TCS"    		
        }
    ],
	"update": [
	     {
		    "canonicalName": "Wipro tech"
			"synonyms": [
                "Wipro technology"
            ]
		 },
		 {
		    "canonicalName": "Infosys"
			"synonyms": [
                "Infosys tech"
            ]
		 }
	]	 	
    "add": [
        {
            "canonicalName": "Apple Computers",
            "synonyms": [
                "Apple"
            ]
        },
        {
            "canonicalName": "Google India",
            "synonyms": ["Google"]
        }
	]
}

So there would be 3 grouping. All the update values will come in update tag, add values in add tag based on OPERATION column and delete in delete tag. ORGNAME value of column will be canonicalName name in file. If synonyms is null then it will not be present else it will be there.

I know JDBC in java. I can read data using executeQuery of Preparedstatement and can display in console using sysout. But I am not able to write data into file in the above format.

Can anybody help me? I am database developer so not able to think how can I do it. Even minimal help would be a lot for me.

I want to convert Resultset into above file, which I am not able to do.

答案1

得分: 2

因为你的信息存储在数据库中,所以将任务分开非常重要。

  1. 从数据库获取信息并转换为对象。
  2. 分离删除、添加、更新的对象。
  3. 打印分离的对象。

任务1已完成,你可以访问和检索数据。

对于任务2,你需要创建一个名为 Data.java 的类,其属性包括 orgName、synonyms 和 operation,都是字符串类型。同时,包括 getter 和 setter 方法。

你可以将这个类视为表中的一条记录。然后,你需要以某种方式生成 Data.java 的列表,以“复制”整个表格。

可以按照以下方式完成:

List<Data> dataList = new ArrayList<>();
// 数据库操作代码
ResultSet rs = pstmt.executeQuery();
while (rs.next) {
    Data data = new Data();
    data.setOrgName(rs.getString("OrgName"));
    data.setSynonyms(rs.getString("Synonyms"));
    data.setOperation(rs.getString("Operation"));

    dataList.add(data);
}

现在,你可以将这个 dataList 打印出来作为对象。

接下来的两个步骤可以一起完成。
对于 dataList 中的每个对象(使用 foreach 循环),你可以开始生成 OrgName.json 文件。重要的是要将删除、添加和修改分组。

可以按照以下方式完成:

JSONObject obj = new JSONObject();
JSONArray delete = new JSONArray();
JSONArray modify = new JSONArray();
JSONArray add = new JSONArray();
for (Data data : dataList) {

    switch (data.getOperation()) {
        case "delete":
            // 表示这是一个删除对象
            JSONObject deleteObj = new JSONObject();
            deleteObj.put("canonicalName", data.getOrgName());
            delete.add(deleteObj);
            break;
        case "add":
            // 表示这是一个添加对象,类似于删除
            // 类似处理
            break;
        case "modify":
            // 表示这是一个修改对象,类似于删除
            // 类似处理
        default:
            break;
    }
}

之后,你可以使用 FileWriter 生成文件。

参考这个链接:将 JSON 对象写入文件执行查询并迭代 ResultSet

英文:

Since you have the information inside a DB, it is important to separate tasks.

  1. Obtain the information. DONE
  2. Convert the information from the DB into an Object
  3. Separate delete, add, update objects
  4. Print the separated objects.

Task 1 is DONE, you can access and retrieve the data.

For task 2 you need to create the Data.java class with the attributes orgName, synonyms and operation as a string type.
*Include getter and setter.

You need to see this class as one register of the Table.
Then you need to somehow generate a list of Data.java to 'replicate' the table.

This can be done like this:

List&lt;Data&gt; dataList = new ArrayList&lt;&gt;();
//Your database code
ResultSet rs = pstmt.executeQuery();
while (rs.next) {
            Data data = new Data();
            data.setOrgName(rs.getString(&quot;OrgName&quot;));
            data.setSynonyms(rs.getString(&quot;Synonyms&quot;));
            data.setOperation(rs.getString(&quot;Operation&quot;));

            dataList.add(data);
        }

You can now print that dataList as objects.

Next two steps can be done together.
For each object inside the dataList (foreach) you can start to generate the OrgName.json file. It is important to group delete, add and modify.

This can be done like this:

    JSONObject obj = new JSONObject();
    JSONArray delete = new JSONArray();
    JSONArray modify = new JSONArray();
    JSONArray add = new JSONArray();
    for (Data data : dataList) {

        switch (data.getOperation()){
            case &quot;delete&quot;:
                //This means that its is a delete object
                JSONObject obj = new JSONObject();
                obj.put(&quot;canonicalName&quot;, data.getOrgName());
                delete.add(obj);
                break;
            case &quot;add&quot;:
                //This means that its is an add object
                // similar to delete
                break;
            case &quot;modify&quot;:
                //This means that its is a modify object
                //Similar to delete
            default:
                break;
        }
    }

After that you can use FileWriter to generate the file.

Take a look to this link: write JSON object to file and execute query and iterate RS

答案2

得分: 1

Jackson是一个非常有用的库,用于处理JSON。

基于你问题中的示例JSON,你可以创建简单的POJO(普通Java对象)来模拟JSON结构,然后利用Jackson的ObjectMapper将POJO映射为包含你想要写入File的JSON的String

以下是一个非常简单的示例,但你需要根据需要更新此示例以适当处理数据隐藏和错误处理。

class OrganizationModificationsDto {

    public List<Organization> delete;
    public List<Organization> update;
    public List<Organization> add;

    public static String toJson(OrganizationModificationsDto dto) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(dto);
    }

}

class Organization {
    public String canonicalName;
    public List<String> synonyms;
}

ObjectMapper还有一个writeValue方法,允许你将JSON直接写入FileWriterOutputStream等。

public void writeValue(File resultFile, Object value)

因此,一旦你构建了OrganizationModificationsDto,你可以直接将其作为JSON写入文件。

objectMapper.writeValue(new File("OrgName.json"), dto);

这里还有一个有用的教程

英文:

Jackson is a very useful library for dealing with JSON.

Based on the example JSON in your question, you could create simple POJOs to model the JSON structure, and then take advantage of Jackson's ObjectMapper to map the POJO to a String containing the JSON you want to write to a File.

A very simple example follows, but you will have to update this example to appropriately deal with data hiding and error handling.

class OrganizationModificationsDto {

    public List&lt;Organization&gt; delete;
    public List&lt;Organization&gt; update;
    public List&lt;Organization&gt; add;

    public static String toJson( OrganizationModificationsDto dto ) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString( dto );
    }

}

class Organization {
    public String canonicalName;
    public List&lt;String&gt; synonyms;
}

ObjectMapper also has a writeValue method that will allow you to write the JSON directly to a File, Writer, OutputStream, etc.

public void writeValue(File resultFile, Object value)

So once you had built up OrganizationModificationsDto, you could just directly write as JSON to a file.

objectMapper.writeValue( new File(&quot;OrgName.json&quot;), dto );

And here is a useful tutorial.

huangapple
  • 本文由 发表于 2020年7月24日 05:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63063456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定