我正在连接到 Oracle 数据库并查询多个表。我当前的代码创建连接并调用包含查询的 PL/SQL 函数。获得结果集后,我将其添加到 Vector(因为我不确定每个查询将产生的记录数)。
我的问题是我不确定如何从 Vector 中写入分隔文件。我想一旦我将我的结果集添加到它,它只是一个巨大的字符串。我需要能够从查询中接收每个字段并在它们之间定界,并保持行分开。
这是我的代码:
public static void main(String[] args) throws SQLException {
// instantiate db connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (Exception e) {
throw new SQLException("Oracle JDBC is not available", e);
}
// define connection string and parameters
String url = "jdbc:oracle:thin:@//host:port/sid";
Connection conn = DriverManager.getConnection(url, "USERNAME","PASSWORD");
CallableStatement stmt = conn.prepareCall("{? = CALL <functionname>(?)}");
// get result set and add to a Vector
ResultSet rs = stmt.executeQuery();
Vector<String> results = new Vector();
while ( rs.next() ){
results.add(rs.getString(1));
}
// close result set, sql statement, and connection
rs.close();
stmt.close();
conn.close();
// write Vector to output file,
// where the file name format is MMddyyyy.txt
try {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
String dateStr = sdf.format(cal.getTime());
FileWriter fwrite = new FileWriter(dateStr + ".txt");
BufferedWriter out = new BufferedWriter(fwrite);
for(int i = 0; i < results.size(); i++)
{
String temp = results.elementAt(i);
out.write(temp);
}
out.close();
}catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
我只是不确定如何从数据库中获取信息并将其写入分隔文件。提前致谢!