| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.samples; |
| 7 |
|
| 8 |
import java.sql.ResultSet; |
| 9 |
import java.sql.ResultSetMetaData; |
| 10 |
import java.sql.SQLException; |
| 11 |
import java.sql.Types; |
| 12 |
|
| 13 |
import org.h2.store.fs.FileUtils; |
| 14 |
import org.h2.tools.Csv; |
| 15 |
import org.h2.tools.SimpleResultSet; |
| 16 |
|
| 17 |
/** |
| 18 |
* This sample application shows how to use the CSV tool |
| 19 |
* to write CSV (comma separated values) files, and |
| 20 |
* how to use the tool to read such files. |
| 21 |
* See also the section CSV (Comma Separated Values) Support in the Tutorial. |
| 22 |
*/ |
| 23 |
public class CsvSample { |
| 24 |
|
| 25 |
/** |
| 26 |
* This method is called when executing this sample application from the |
| 27 |
* command line. |
| 28 |
* |
| 29 |
* @param args the command line parameters |
| 30 |
* @throws SQLException on failure |
| 31 |
*/ |
| 32 |
public static void main(String... args) throws SQLException { |
| 33 |
CsvSample.write(); |
| 34 |
CsvSample.read(); |
| 35 |
FileUtils.delete("data/test.csv"); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Write a CSV file. |
| 40 |
*/ |
| 41 |
static void write() throws SQLException { |
| 42 |
SimpleResultSet rs = new SimpleResultSet(); |
| 43 |
rs.addColumn("NAME", Types.VARCHAR, 255, 0); |
| 44 |
rs.addColumn("EMAIL", Types.VARCHAR, 255, 0); |
| 45 |
rs.addColumn("PHONE", Types.VARCHAR, 255, 0); |
| 46 |
rs.addRow("Bob Meier", "[email protected]", "+41123456789"); |
| 47 |
rs.addRow("John Jones", "[email protected]", "+41976543210"); |
| 48 |
new Csv().write("data/test.csv", rs, null); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Read a CSV file. |
| 53 |
*/ |
| 54 |
static void read() throws SQLException { |
| 55 |
ResultSet rs = new Csv().read("data/test.csv", null, null); |
| 56 |
ResultSetMetaData meta = rs.getMetaData(); |
| 57 |
while (rs.next()) { |
| 58 |
for (int i = 0; i < meta.getColumnCount(); i++) { |
| 59 |
System.out.println( |
| 60 |
meta.getColumnLabel(i + 1) + ": " + |
| 61 |
rs.getString(i + 1)); |
| 62 |
} |
| 63 |
System.out.println(); |
| 64 |
} |
| 65 |
rs.close(); |
| 66 |
} |
| 67 |
|
| 68 |
} |