簡體   English   中英

如何在java中從MySQL檢索查詢的結果集

[英]How to retrieve result set of a query from MySQL in 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?
}

這是我想要存儲在該數據庫中的arraylist:

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

並且這些對象存儲在arraylist中:

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

我需要使用什么通用代碼來將arraylist存儲在MySQL數據庫中? 我需要使用什么通用代碼才能將arraylist從MySQL數據庫中刪除?

這是用於檢索和填充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/

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

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;

如果要插入,則選擇不是方法。 你需要的是什么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM