简体   繁体   中英

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

first time posting so sorry if my question is slightly strange.

So I have a project in school that requires us to create java classes using netbeans that open up a window with three options, check stock, purchase item and update stock.

We had a class called stockdata that held the details of 5 different items for us to use in our three classes to check, purchase and update items. The latest stage of our coursework requires us to create a derby database and enter the items into a table.

I have done this with no issues but I am having a problem getting the items from the table back into my classes to use. We were given the following code but I can't get it to work, even using the commented hints.

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);
    }
}

}

Sorry if this seems a stupid question but I am fairly new to Java and was making good progress until this roadblock.

Thanks in advance!

Alex

Searching for "java sql" on Google delivers this link: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

From a connection you can create a statement (you can find this in the link and in your code) , then fetch a result set and loop over that with rs.next(). That should get your started.

Of course you have to make sure that the driver and database are there/running, just saying...

Here netbeans has nothing to do with database. This is a Java-based integrated development environment(IDE) that will help you to reduce syntactic error.

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 ; } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM