簡體   English   中英

如何將數據庫中的表中的數據調用到netbeans中的Java類中?

[英]How do I call data from a table in a database into a java class in netbeans?

第一次發帖,如果我的問題有點奇怪,對不起。

因此,我在學校有一個項目,要求我們使用netbeans創建Java類,這將打開一個包含三個選項的窗口:檢查庫存,購買物料和更新庫存。

我們有一個名為stockdata的類,其中包含5種不同物品的詳細信息,供我們在三個類中使用以檢查,購買和更新物品。 我們課程的最新階段要求我們創建一個德比數據庫,並將項目輸入表格中。

我這樣做沒有問題,但是在將表中的項目放回類中使用時遇到了問題。 我們得到了以下代碼,但是即使使用注釋的提示,我也無法正常工作。

package stock;

// Skeleton version of StockData.java that links to a database.
// NOTE: You should not have to make any changes to the other
// Java GUI classes for this to work, if you complete it correctly.
// Indeed these classes shouldn't even need to be recompiled
import java.sql.*; // DB handling package
import java.io.*;
import org.apache.derby.drda.NetworkServerControl;

public class StockData {

    private static Connection connection;
    private static Statement stmt;

    static {
    // standard code to open a connection and statement to an Access         database
        try {
            NetworkServerControl server = new NetworkServerControl();
            server.start(null);
            // Load JDBC driver
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            //Establish a connection
            String sourceURL = "jdbc:derby://localhost:1527/"
                    + new File("UserDB").getAbsolutePath() + ";";
            connection = DriverManager.getConnection(sourceURL, "use",   "use");
            stmt = connection.createStatement();
    } // The following exceptions must be caught
    catch (ClassNotFoundException cnfe) {
        System.out.println(cnfe);
    } catch (SQLException sqle) {
        System.out.println(sqle);
    } catch (Exception e) {
        System.out.println(e);
    }

}

// You could make methods getName, getPrice and getQuantity simpler by using an auxiliary
// private String method getField(String key, int fieldNo) to return the appropriate field as a String
public static String getName(String key) {
    try {
        // Need single quote marks ' around the key field in SQL. This is easy to get wrong!
        // For instance if key was "11" the SELECT statement would be:
        // SELECT * FROM Stock WHERE stockKey = '11'
        ResultSet res = stmt.executeQuery("SELECT * FROM Stock WHERE stockKey = '" + key + "'");
        if (res.next()) { // there is a result
            // the name field is the second one in the ResultSet
            // Note that with  ResultSet we count the fields starting from 1
            return res.getString(2);
        } else {
            return null;
        }
    } catch (SQLException e) {
        System.out.println(e);
        return null;
    }
}

public static double getPrice(String key) {
    // Similar to getName. If no result, return -1.0
    return 0;
}

public static int getQuantity(String key) {
    // Similar to getName. If no result, return -1

    return 0;
}

// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
    // SQL UPDATE statement required. For instance if extra is 5 and stockKey is "11" then updateStr is
    // UPDATE Stock SET stockQuantity = stockQuantity + 5 WHERE stockKey = '11'
    String updateStr = "UPDATE Stock SET stockQuantity = stockQuantity + " + extra + " WHERE stockKey = '" + key + "'";
    System.out.println(updateStr);
    try {
        stmt.executeUpdate(updateStr);
    } catch (SQLException e) {
        System.out.println(e);
    }
}

// close the database
public static void close() {
    try {
        connection.close();
    } catch (SQLException e) {
        // this shouldn't happen
        System.out.println(e);
    }
}

}

抱歉,這似乎是一個愚蠢的問題,但是我對Java還是很陌生,並且在取得這一障礙之前一直取得良好進展。

提前致謝!

亞歷克斯

在Google上搜索“ java sql”會提供以下鏈接: https : //docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

從連接中,您可以創建一條語句(可以在鏈接和代碼中找到該語句),然后獲取結果集並使用rs.next()對其進行循環。 那應該讓您開始。

當然,您必須確保驅動程序和數據庫在那里/正在運行,只是說...

在這里,netbeans與數據庫無關。 這是一個基於Java的集成開發環境(IDE),它將幫助您減少語法錯誤。

public void dataAccess(){

try { String connectionUrl = "suitable connection url as per your database"; Connection con = null; Statement stmt = null; ResultSet rs = null; Class.forName("JDBC driver name as per your database"); con = DriverManager.getConnection(connectionUrl, userName, password); String SQL = "SQL query as per your criteria"; stmt = con.createStatement(); rs = stmt.executeQuery(query); while (rs.next()) { // look into ResultSet api and use method as per your requirement } rs.close(); } catch (Exception e) { //log error message ; } }

暫無
暫無

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

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