简体   繁体   English

如何将数据库中的表中的数据调用到netbeans中的Java类中?

[英]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. 因此,我在学校有一个项目,要求我们使用netbeans创建Java类,这将打开一个包含三个选项的窗口:检查库存,购买物料和更新库存。

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. 我们有一个名为stockdata的类,其中包含5种不同物品的详细信息,供我们在三个类中使用以检查,购买和更新物品。 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. 抱歉,这似乎是一个愚蠢的问题,但是我对Java还是很陌生,并且在取得这一障碍之前一直取得良好进展。

Thanks in advance! 提前致谢!

Alex 亚历克斯

Searching for "java sql" on Google delivers this link: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html 在Google上搜索“ java sql”会提供以下链接: 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(). 从连接中,您可以创建一条语句(可以在链接和代码中找到该语句),然后获取结果集并使用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. 在这里,netbeans与数据库无关。 This is a Java-based integrated development environment(IDE) that will help you to reduce syntactic error. 这是一个基于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.

相关问题 我如何将mysql的数据库连接方法存储在java netbeans类中,并在需要时在jFrame中调用它 - how do i store Database connectivity methods of mysql in a java netbeans class and call it whenever i need it in a jFrame 如何使用Java将数据从4个文本字段发送到Netbeans中的Derby数据库 - How do I send data from 4 text fields to a Derby Database in Netbeans using Java 如何在 Java (Netbeans) 中创建表格? - How can I do a table in Java (Netbeans)? 如何在Java中从另一个类(非继承)调用一个类? - How do I call a class from another class(not inheritance) in Java? 如何从另一个Java类调用JFrame [Netbeans] - How to call JFrame from another Java class [Netbeans] 如何将变量从Java类调用到另一个类? - How do I call variables from a Java class into another Class? 如何从java中的类调用另一个类 - How do I call a another class from a class in java 如何从另一个类中的Java类调用变量 - How do I call variables from a Java class in another Class 如何从Netbeans,Java DB(Derby)数据库导出表 - How to export table from Netbeans, Java DB (Derby) Database 如何使用查询从 MySQL 数据库中检索单个单元格并将其分配给 Java Netbeans ZE9714F33DDD59 中的变量 - How do I retrieve a single cell from MySQL database using query and assigned it to a variable in Java Netbeans Apache
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM