2012-08-07 60 views
2

我已經連接到我的數據庫:如何檢索查詢結果集的從MySQL中的Java

Connection con = DriverManager.getConnection(
    "jdbc:mysql://instance23389.db.xeround.com:15296/Inventory","user","password"); 
PreparedStatement Statement = con.prepareStatement("Select * from inventory"); 
ResultSet result = Statement.executeQuery(); 
while(result.next()) { 
    //What to put here? 
} 

這就是我要存儲在數據庫中的數組列表:

static ArrayList<Product> Chart=new ArrayList<Product>(); 

這已存儲在ArrayList中這些對象:

double Total; 
String name; 
double quantity; 
String unit; 
double ProductPrice; 

什麼是通用代碼,我需要使用獲得的ArrayList存儲在MySQL數據庫中? 我需要用什麼通用代碼才能將數組列表從MySQL數據庫中取出?

+1

我很困惑你真正想要什麼。你想獲取信息或插入信息到數據庫? – 2012-08-07 23:40:51

+1

[從結果集中獲取數據](http://www.exampledepot.com/egs/java.sql/GetRsData.html) – 2012-08-07 23:42:08

+0

但他也提到他需要將數組列表存儲在數據庫中。 – 2012-08-07 23:44:45

回答

7

這是一個什麼樣用於檢索&填充的ArrayList productList

while (result.next()) { 

    Product product = new Product(); 

    product.setTotal(result.getDouble("Total")); 
    product.setName(result.getString("Name")); 
    // etc. 

    productList.add(product); 
} 

同時一個模板,我邀請您來看看:

http://www.jdbc-tutorial.com/

1

如果你想插入,那麼選擇不是這樣。你需要的是像

Statement statement = conn.createStatement(); 
statement.executeUpdate("INSERT INTO Customers " + "VALUES (1001, 'Simpson', 'Mr.', 'Springfield', 2001)"); 
1

你的問題不是很清楚,但我猜你想要的東西是這樣的:

List<Product> products = new ArrayList<Product>(); 

String host = "instance23389.db.xeround.com"; 
int port = 15296; 
String dbName = "Inventory"; 
String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName; 

Connection con = null; 
PreparedStatement stmt = null; 

try { 

    con = DriverManager.getConnection(url, "user","password"); 
    stmt = con.prepareStatement("select * from inventory"); 
    ResultSet result = stmt.executeQuery(); 
    while(result.next()) { 
    Product prod = new Product(); 
    prod.setTotal(result.getDouble("total")); 
    prod.setName(result.getString("name")); 
    prod.setQuantity(result.getDouble("quantity")); 
    prod.setUnit(result.getString("unit")); 
    prod.setProductPrice(result.getDouble("product_price")); 
    products.add(prod); 
    } 
} finally { 
    if (stmt != null) { 
    try { 
     stmt.close(); 
    } catch (SQLException ex) { 
    } 
    } 
    if (con != null) { 
    try { 
     con.close(); 
    } catch (SQLException ex) { 
    } 
    } 
} 
return products;