简体   繁体   English

如何使我的Java代码与需要从中提取数据然后将其写回到Excel文件的数据库中的所有表兼容

[英]How can I make my java code compatible with all the tables in database from which I need to extract the data and then writing it back to Excel file

There is a database (northwind) on my machine and I have to write a code in java so as to extract the data from the table (Customers) stored in the database. 我的机器上有一个数据库(逆风) ,我必须用Java编写代码,以便从数据库中存储的表(客户)中提取数据。

If this was only specific to Customers table then I would have done it but I want to make my code generic so that I can extract data from other tables also by simply giving the name of the table in a string variable. 如果这仅是针对Customers表的,那么我会做的,但是我想使代码通用,这样我也可以通过简单地在字符串变量中给出表的名称来从其他表中提取数据。

Please have a look to my code. 请看一下我的代码。

Main class 主班

package main;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import model.TableModel;
import service.DBConnection;
import service.WriteExcel;

public class Main {

public static void main(String[] args) throws SQLException, ClassNotFoundException {

    double start = System.nanoTime();
    String tableName = "Customers";
    Class<?> c = Class.forName(tableName);
    Connection conn = new DBConnection().getConnection();
    System.out.println("Connection Established");

    QueryRunner run = new QueryRunner();
    ResultSetHandler<List<TableModel>> resultHandler = new BeanListHandler<TableModel>(c.getClass())
    List<TableModel> data = run.query(conn, "SELECT * FROM `" + tableName + "`;",
            resultHandler);

    WriteExcel we = new WriteExcel(tableName+"_sheet", new File(tableName+".xlsx"));
    we.writeMultipleRows(data);
    we.writeWorkbookToFile();
    System.out.println("File Written Succesfully");
    conn.close();

    System.out.println("Time Taken: " + (System.nanoTime()-start)/1000000+" ms");

}

}

In the above code, at line 27, If the statement would have been as follows 在上面的代码中,在第27行,如果语句如下

ResultSetHandler<List<TableModel>> resultHandler = new BeanListHandler<TableModel>(Customers.class);

This is running perfectly, as I said I want this statement to be independent of the table name, making my code more general. 正如我说过的,我希望此语句与表名无关,这使我的代码更通用。

TableModel 表格模型

package model;

import java.util.List;

public interface TableModel {

public List<String> getObjectAsList();

}

Customers 顾客

package model;

import java.util.ArrayList;
import java.util.List;

public class Customers implements TableModel {

private String customerId;
private String companyName;
private String contactName;
private String contactTitle;
private String address;
private String city;
private String region;
private String postalCode;
private String country;
private String phone;
private String fax;


public String getCustomerId() {
    return customerId;
}

public void setCustomerId(String customerId) {
    this.customerId = customerId;
}

public String getCompanyName() {
    return companyName;
}

public void setCompanyName(String companyName) {
    this.companyName = companyName;
}

public String getContactName() {
    return contactName;
}

public void setContactName(String contactName) {
    this.contactName = contactName;
}

public String getContactTitle() {
    return contactTitle;
}

public void setContactTitle(String contactTitle) {
    this.contactTitle = contactTitle;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getRegion() {
    return region;
}

public void setRegion(String region) {
    this.region = region;
}

public String getPostalCode() {
    return postalCode;
}

public void setPostalCode(String postalCode) {
    this.postalCode = postalCode;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getFax() {
    return fax;
}

public void setFax(String fax) {
    this.fax = fax;
}

public List<String> getObjectAsList(){
    List<String> fields = new ArrayList<>();
    fields.add(customerId);
    fields.add(companyName);
    fields.add(contactName);
    fields.add(contactTitle);
    fields.add(address);
    fields.add(city);
    fields.add(region);
    fields.add(postalCode);
    fields.add(country);
    fields.add(phone);
    fields.add(fax);
    return fields;
}

@Override
public String toString() {
    return "{ CustomerID = "+getCustomerId()+","
            + " CompanyName = "+getCompanyName()+","
            + " ContactName = "+getContactName()+","
            + " ContactTitle = "+getContactTitle()+","
            + " Address = "+getAddress()+","
            + " City = "+getCity()+","
            + " Region = "+getRegion()+","
            + " PostalCode = "+getPostalCode()+","
            + " Country = "+getCountry()+","
            + " Phone = "+getPhone()+","
            + " Fax = "+getFax()+"}";
}

}

I have used DbUtils library for extracting database. 我已使用DbUtils库提取数据库。 Any further suggestion for enhancing my code is welcomed. 我们欢迎任何进一步增强我的代码的建议。

If I understand your question right, you could try something like below. 如果我正确理解您的问题,则可以尝试以下操作。

To query the table, you can use run.query(SQL, ResultHandler) . 要查询该表,可以使用run.query(SQL, ResultHandler)

    ResultSetHandler<List<Map<String, Object>>> resultHandler = genericResultHandler();

    List<Map<String, Object>> result = null;

    // Execute the SQL statement and return the results in a List of
    // T objects generated by the BeanListHandler.
    try
    {
        result = run.query(sqlQuery, resultHandler, varargs);
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }

    result.stream().forEach(System.out::println);

The interesting part here is the private method genericResultHandler . 有趣的是私有方法genericResultHandler For demonstration purposes, I used a HashMap to store the values and the corresponding cloumn names. 出于演示目的,我使用了HashMap来存储值和相应的Cloumn名称。

private ResultSetHandler<List<Map<String, Object>>> genericResultHandler()
{
    return new ResultSetHandler<List<Map<String, Object>>>()
    {
        @Override
        public List<Map<String, Object>> handle(java.sql.ResultSet rs) throws SQLException
        {
            List<Map<String, Object>> result = new ArrayList<>();

            // Query all rows of the table.
            while (rs.next())
            {
                // Get metadata of the table.
                java.sql.ResultSetMetaData meta = rs.getMetaData();
                int cols = meta.getColumnCount();
                Map<String, Object> data = new HashMap<>();

                // For each column store column name and value of the cell into the hashmap.
                for (int i = 1; i < cols; i++)
                {
                    String colName = meta.getColumnName(i);
                    Object value = rs.getObject(colName);
                    data.put(colName, value);
                }

                // Add the row to the result list. 
                result.add(data);
            }

            return result;
        }
    };
}

Afterwards some imports I have used: 之后,我使用了一些导入:

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

Output would be something like this (for my test table): 输出将是这样的(对于我的测试表):

{month=JANUARY, temperature=1.6, globalradiation=0.0, monthid=1}
{month=FEBRUARY, temperature=-0.9, globalradiation=0.0, monthid=2}
{month=MARCH, temperature=0.9, globalradiation=0.0, monthid=3}
{month=APRIL, temperature=7.2, globalradiation=0.0, monthid=4}
{month=MAY, temperature=14.1, globalradiation=0.0, monthid=5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使我的泛型代码与此方法签名兼容? - How can I make my generics code compatible with this method signature? 我如何制作一个从Excel文件动态地拾取数据的Java程序? - How can i make a java program that dynamicaly picks up data from an excel file? 如何让我的代码循环回到 Java 的开头? - How do I make my code loop back to the beginning in Java? 如何将数据从 PHPMyAdmin 数据库获取到 Java 代码中? - How can I get data from a PHPMyAdmin database into java code? 我如何在我的应用程序的所有页面中显示从后端检索的值 - how can i display a value which is retrieved from the back end in all the pages of my application 如何使我的文件读取/写入程序更快? - How can I make my file reading/writing program faster? 如何阻止我的bufferedWriter重写文件中已经存在的文本? - How can I stop my bufferedWriter from re-writing the text which is already in the file? 我可以使.jar文件与旧版本的java兼容 - can i make .jar file compatible with older versions of java 如何从“[”开始的 Json 中提取数据? - how can I extract data from Json which start from “[”? 如何从Java中的XML文件提取所有PCDATA(文本)? - How can I extract all PCDATA (text) from an XML file in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM