4

我已经连接到我的数据库:

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 数据库中取出?

4

3 回答 3

11

这是用于检索和填充 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/

于 2012-08-07T23:48:04.083 回答
3

你的问题不是很清楚,但我猜你想要这样的东西:

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;
于 2012-08-07T23:48:42.917 回答
1

如果要插入,则选择不是方法。你需要的是类似

Statement statement = conn.createStatement();
statement.executeUpdate("INSERT INTO Customers " + "VALUES (1001, 'Simpson', 'Mr.', 'Springfield', 2001)");
于 2012-08-07T23:46:23.773 回答