我创建了一个连接到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);
}
}
答案 0 :(得分:0)
将您声明的array
声明为私有变量,在静态块中初始化它并为其添加getter和setter方法。这里没有使用getter-setter,但这仅供您理解。
FruitDatabase.java
public class FruitDatabase {
private static String[] array;
public static String[] getArray() {
return array;
}
public static void setArray(String[] arr) {
array = arr;
}
public static void main(String[] args) throws Exception {
...
}
private static void outputResultSet(ResultSet rs) throws Exception {
...
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
array[i] = rs.getString(i);
System.out.println(array[i]);
}
setArray(array);
....
}
....
}
然后从另一个类(假设Display.java),你需要创建这个类的对象,然后你可以访问这个数组:
Display.java
public class Display {
public static void main(String[] args) {
String[] newArr = new String[FruitDatabase.getArray().length];
int i=0;
for(String s : FruitDatabase.getArray()){
System.out.println(s);
newArr[i++]=s;
}
}
}