如何使用jdbc将整个表写入平面文件(文本文件)?到目前为止,我尝试了以下内容:
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM tablename");
BufferedInputStream buffer;
FileOutputStream out = new FileOutputStream("flatfile.txt");
while(result.next() )
{
buffer = new BufferedInputStream(result.getBinaryStream("????") );
byte[] buf = new byte[4 * 1024]; //4K buffer
int len;
while( (len = buffer.read(buf, 0, buf.length) ) != -1 )
{
out.write(buf, 0, len );
}
}
out.close();
“????”只是我的占位符.我被困在作为论点传递的内容上.
解决方法:
您可以使用下面的代码从表中获取所有列名和整个数据.
writeToFile方法将包含写入文件的逻辑(如果那不够明显:))
ResultSetMetaData metadata = rs.getMetaData();
int columnCount = metadata.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
writeToFile(metadata.getColumnName(i) + ", ");
}
System.out.println();
while (rs.next()) {
String row = "";
for (int i = 1; i <= columnCount; i++) {
row += rs.getString(i) + ", ";
}
System.out.println();
writeToFile(row);
}