<dependency>
<groupId>com.github.albfernandez</groupId>
<artifactId>javadbf</artifactId>
<version>1.13.2</version>
</dependency>
@org.junit.jupiter.api.Test
public void resultSetToDbf() {
MySQLDBUtil mySQLDBUtil = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Database database = DataBaseUtil.getDataBase(0);
mySQLDBUtil = new MySQLDBUtil(database);
connection = mySQLDBUtil.getConnection();
String sql = "select * from event_table";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery(sql);
DbfUtil.createDbf("E:\\test.dbf",resultSet, "gbk");
} catch (SQLException e) {
e.printStackTrace();
} finally {
MySQLDBUtil.closeAllS(resultSet, preparedStatement, connection);
}
}
package com.parameter.tools;
import com.linuxense.javadbf.DBFDataType;
import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFWriter;
import java.io.*;
import java.nio.charset.Charset;
import java.sql.*;
import java.text.SimpleDateFormat;
public class DbfUtil {
public static void createDbf(String path, ResultSet crs, String charsetName) {
DBFWriter dbfWriter = null;
try {
ResultSetMetaData metaData = crs.getMetaData();
int columnCount = metaData.getColumnCount();
DBFField[] fields = new DBFField[columnCount];
for (int i = 1; i <= columnCount; i++) {
DBFField field = new DBFField();
String columnName = metaData.getColumnName(i);
field.setName(columnName);
field.setType(DBFDataType.CHARACTER);
field.setLength(metaData.getPrecision(i));
fields[i-1] = field;
}
dbfWriter = new DBFWriter(new FileOutputStream(path), Charset.forName(charsetName));
dbfWriter.setFields(fields);
while (crs.next()) {
Object[] rowData = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
if(crs.getObject(i).getClass().getName().equals("java.sql.Timestamp")){
Timestamp timestamp = (Timestamp) crs.getObject(i);
Date date = new Date(timestamp.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
rowData[i-1] = sdf.format(date);
}else{
rowData[i-1] = crs.getString(i);
}
}
dbfWriter.addRecord(rowData);
}
} catch (FileNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
ByteArray.closeStream(dbfWriter);
}
}
}
|