如何使用 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);
}
以下是我如何从 JDBC 连接转储表,如果您想查看内存(例如:HSQL)数据库中的所有行,这对于调试非常有用:
public static void spitOutAllTableRows(String tableName, Connection conn) {
try {
System.out.println("current " + tableName + " is:");
try (PreparedStatement selectStmt = conn.prepareStatement(
"SELECT * from " + tableName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = selectStmt.executeQuery()) {
if (!rs.isBeforeFirst()) {
System.out.println("no rows found");
}
else {
System.out.println("types:");
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
System.out.print(rs.getMetaData().getColumnName(i + 1) + ":" + rs.getMetaData().getColumnTypeName(i + 1) + " ");
}
System.out.println();
while (rs.next()) {
for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
System.out.print(" " + rs.getMetaData().getColumnName(i) + "=" + rs.getObject(i));
}
System.out.println("");
}
}
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
输出就像
current <yourtablename> is:
types:ID:INT YOURCOLUMN1:VARCHAR YOURCOLUMN2:VARCHAR
ID=1 YOURCOLUMN1=abc YOURCOLUMN2=null
ID=2 YOURCOLUMN1=def YOURCOLUMN2=ghi
...
result.getBinaryStream("????")
将仅返回您作为占位符放置的该列的值。
如果要获取所有列,则需要使用
ResultSetMetaData
中的
ResultSet
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
for (int i=1; i<=columnCount; i++)
{
String columnName = metadata.getColumnName(i);
System.out.println(columnName);
}
语句 st = con.createStatement(); 结果集 rs=st.executeQuery(Queryall);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
System.out.print(metaData.getColumnName(i) + " ");
}
System.out.println();
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
con.close();
System.out.println("Connection Closed");