我创建了一个要连接到 derby 数据库的类。 在程序里, 我创建了表格, 并插入了一些水果名称作为值 。 我只是想知道我如何能够创建另一个类, 在新的阵列中获取水果名称值 。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class FruitDatabase {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("drop table fruit");
stmt.executeUpdate("create table fruit (name CHAR(15))");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Apple )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Orange )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Banana )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Pineapple )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Mango )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Kiwi )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Grape )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Strawberry )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Pear )");
stmt.executeUpdate("INSERT INTO fruit(name)VALUES( Peach )");
ResultSet rs = stmt.executeQuery("SELECT * FROM fruit");
outputResultSet(rs);
rs.close();
stmt.close();
conn.close();
}
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
String array [] = new String [numberOfColumns + 1];
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
array[i] = rs.getString(i);
System.out.println(array[i]);
}
}
}
private static Connection getConnection() throws Exception {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String url = "jdbc:derby:MyDbTest;create=true";
return DriverManager.getConnection(url);
}
}