簡體   English   中英

如何在多個for循環內執行SQL查詢?

[英]How do I execute SQL queries inside multiple for loops?

我正在開發一個涉及Access數據庫集成的Java程序。 該計划的目的是跟上碼頭的停車位和服務。 服務部分的項目偵聽器是一系列的for循環,旨在節省從必須單獨列出每個服務的時間。 但是,這些結果是更新數據庫所必需的,到目前為止,當使用程序的GUI且Access Database在我選擇的任何指定表中均未更新時,尚未進行任何更改。 當GUI處於活動狀態時,我從復選框中選擇了一個選項;當我這樣做時,數據庫將執行。 當我選擇第二個復選框時,無論我選擇什么,它只會導致異常錯誤。 我需要修改程序和/或數據庫,但是我不知道如何解決這種情況。 我的代碼在下面列出,任何幫助將不勝感激。

package marinaProject;

/** Services, repairs, and provisions that are provided at a marina.
 * @author Chris Cardenas
 */

 import javax.swing.*;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.awt.*;
 import java.awt.event.*;
 import java.sql.ResultSet;
 import java.util.Arrays;
 import java.util.Random;
 import java.sql.*;
 import javax.swing.border.*;
 import java.sql.SQLException;

import java.sql.Statement;

public class Services extends JFrame {

static final String DATABASE_URL = "jdbc:ucanaccess://V:/Desktop/MarinaFinal.accdb";
Connection connection = null;
Statement statement = null;
ResultSet result = null;

JTabbedPane tabbedPane = new JTabbedPane();

private JPanel mainPanel = new JPanel(),
        buttonPanel = new JPanel(),
        servicesPanel = new JPanel(),
        repairsPanel = new JPanel(),
        provisionsPanel = new JPanel();

private final int NSERVICES = 6;
private final int NREPAIRS = 4;
private final int NPROVISIONS = 5;

private JCheckBox servicesPackages[] = new JCheckBox[NSERVICES];
private String servicePackageLabels[] = {"Fuel \n", "Water \n", "Waste \n", "Paint \n", "Winter \n", "Charging \n"};
private double servicePrice[] = {4, 3, 4, 7, 10, 0};
String serviceDbStatement;

private JCheckBox repairsPackages[] = new JCheckBox[NREPAIRS];
private String repairPackageLabels[] = {"Mechanical \n", "Electrical \n", "Communication \n", "Navigation \n"};
private double repairPrice[] = {100, 212, 100, 150};
String repairsDbStatement;

private JCheckBox provisionsPackages[] = new JCheckBox[NPROVISIONS];
private String provisionPackageLabels[] = {"Ice \n", "First Aid Kit \n", "Chips \n", "Popcorn \n", "Soda \n"};
private double provisionsPrice[] = {5, 10, 3, 2, 2};
String provisionsDbStatement;

private double totalBill;
private String servicesPrinted[] = new String[6];
private String repairsPrinted[] = new String[4];
private String provisionsPrinted[] = new String[5];
private double servicesPricesPrinted[] = new double[6];
private double repairsPricesPrinted[] = new double[4];
private double provisionsPricesPrinted[] = new double[5];
private int serviceNumber = 0;
private double boatID = 12345;

private JButton doneButton = new JButton("Done");

public Services() {
    setTitle("Services");

    mainPanel.setLayout(new GridLayout(2, 1, 1, 1));

    doneButton.addActionListener(new ActionListen());
    buttonPanel.add(doneButton);

    servicesPanel.setLayout(new BoxLayout(servicesPanel, BoxLayout.Y_AXIS));
    servicesPanel.setBorder(new TitledBorder("Services"));

    for (int i = 0; i < servicesPackages.length; i++) {
        servicesPackages[i] = new JCheckBox(servicePackageLabels[i]);
        servicesPanel.add(servicesPackages[i]);
        servicesPackages[i].addItemListener(new ItemListen());
    }
    tabbedPane.addTab("Services", null, servicesPanel, "Services Information");

    repairsPanel.setLayout(new BoxLayout(repairsPanel, BoxLayout.Y_AXIS));
    repairsPanel.setBorder(new TitledBorder("Repairs"));

    for (int i = 0; i < repairsPackages.length; i++) {
        repairsPackages[i] = new JCheckBox(repairPackageLabels[i]);
        repairsPanel.add(repairsPackages[i]);
        repairsPackages[i].addItemListener(new ItemListen());
    }
    tabbedPane.addTab("Repairs", null, repairsPanel, "Repairs Information");

    provisionsPanel.setLayout(new BoxLayout(provisionsPanel, BoxLayout.Y_AXIS));
    provisionsPanel.setBorder(new TitledBorder("Provisions"));

    for (int i = 0; i < provisionsPackages.length; i++) {
        provisionsPackages[i] = new JCheckBox(provisionPackageLabels[i]);
        provisionsPanel.add(provisionsPackages[i]);
        provisionsPackages[i].addItemListener(new ItemListen());
    }
    tabbedPane.addTab("Provisions", null, provisionsPanel, "Provisions Information");

    tabbedPane.setTabPlacement(SwingConstants.LEFT);
    mainPanel.add(tabbedPane);
    mainPanel.add(buttonPanel);
    add(mainPanel);

    Random rand = new Random();

    serviceNumber = rand.nextInt(5000) + 1;
}

private class ItemListen implements ItemListener {

    public void itemStateChanged(ItemEvent event) {
        totalBill = 0;
        for (int i = 0; i < servicesPackages.length; i++) {
            if (servicesPackages[i].isSelected()) {
                totalBill += servicePrice[i];
                servicesPrinted[i] = servicePackageLabels[i];
                servicesPricesPrinted[i] = servicePrice[i];
                ResultSet serviceDbResult = null;
                String servicesQuery;
            }
        }

        for (int i = 0; i < repairsPackages.length; i++) {
            if (repairsPackages[i].isSelected()) {
                totalBill += repairPrice[i];
                repairsPrinted[i] = repairPackageLabels[i];
                repairsPricesPrinted[i] = repairPrice[i];
                ResultSet repairsDbResult = null;
                String repairssQuery;
            }
        }

        for (int i = 0; i < provisionsPackages.length; i++) {
            if (provisionsPackages[i].isSelected()) {
                totalBill += provisionsPrice[i];
                provisionsPrinted[i] = provisionPackageLabels[i];
                provisionsPricesPrinted[i] = provisionsPrice[i];
                ResultSet provisionsDbResult = null;
                String provisionsQuery;
                String DATABASE_URL = "jdbc:ucanaccess://V:/Desktop/MarinaFinal.accdb";
            }
        }

        String DATABASE_URL = "jdbc:ucanaccess://V:/Desktop/MarinaFinal.accdb";
        try {
            {
                //establish connection to database
                connection = DriverManager.getConnection(DATABASE_URL);
                System.out.println("Made a connection");

                //create Statement for querying database
                statement = connection.createStatement();
                System.out.println("Established statement");

                //SQL Query
                String sql = "INSERT INTO Services (serviceNumber, boatID, repairMech, repairElectro, serviceWater, serviceWaste, serviceWinter,"
                        + "serviceCharging, servicePaint, serviceFuel, repairCommunication, repairNavigation, provisionIce"
                        + "provisionFirstAid, provisionChips, provisionPopcorn, provisionSoda, slipNumber, billNumber)"
                        + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

                // TEMPORARY VARIABLES
                int slipNumTEMP = 4;
                int billnumTEMP = 454;

                PreparedStatement ps1 = connection.prepareStatement(sql);

                ps1.setDouble(1, serviceNumber);
                ps1.setDouble(2, boatID);
                ps1.setDouble(3, servicePrice[0]);
                ps1.setDouble(4, servicePrice[1]);
                ps1.setDouble(5, servicePrice[2]);
                ps1.setDouble(6, servicePrice[3]);
                ps1.setDouble(7, servicePrice[4]);
                ps1.setDouble(8, servicePrice[5]);
                ps1.setDouble(9, repairPrice[0]);
                ps1.setDouble(10, repairPrice[1]);
                ps1.setDouble(11, repairPrice[2]);
                ps1.setDouble(12, repairPrice[3]);
                ps1.setDouble(13, provisionsPrice[0]);
                ps1.setDouble(14, provisionsPrice[1]);
                ps1.setDouble(15, provisionsPrice[2]);
                ps1.setDouble(16, provisionsPrice[3]);
                ps1.setDouble(17, provisionsPrice[4]);
                ps1.setDouble(18, slipNumTEMP);
                ps1.setDouble(19, billnumTEMP);

                // Execute Query
                int rs = ps1.executeUpdate();
                if (rs == 1) {
                    System.out.println("Query executed");
                } else {
                    System.out.println("Not found.");
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private class ActionListen implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        String label = doneButton.getText();

        if (e.getSource() == doneButton) {
            if (label.equals("Done")) {
                setVisible(false);
                billGUI nextScreen = new billGUI(totalBill, servicesPrinted, repairsPrinted,
                        provisionsPrinted, servicesPricesPrinted, repairsPricesPrinted,
                        provisionsPricesPrinted);
                nextScreen.setSize(400, 650);
                nextScreen.setVisible(true);
            }
        }
    }
}
}

編輯:下面是服務表的圖像以及與數據庫中其他表的關系。

設計視圖中的服務表

表之間的關系

當屏幕快照顯示GUI形式時,會重現您的問題,此修復程序將歸結到您的SQL上,在仔細閱讀后仍會保留語法錯誤,並且缺少逗號。

Java GUI程序

就在provisionIce之后,您沒有逗號,因此由於換行而導致查詢嘗試插入到不存在的列中provisionIceprovisionFirstAid ,這可能會輸出違反Integrity Constraints Violation的行為 ,該行為在MSAccess.exe中將輸出以下兩者之一:

查詢值和目標字段的數量不相同。

INSERT INTO語句包含未知字段名稱“ provisionIceprovisionFirstAid”。

因此,只需添加所需的逗號:

"repairCommunication, repairNavigation, provisionIce,"
----------------------------------------------------^  
 + "provisionFirstAid, provisionChips, provisionPopcorn, provisionSoda,

補充筆記:

  1. 到目前為止,每個復選框單擊都會在所有列中附加相同的確切數據。 可能您仍處於沙盒開發模式。
  2. 考慮在啟動GUI程序的過程中以不同的調用方法連接到Access數據庫,然后在每次單擊復選框時僅在連接對象后附加。 現在,連接是在Listener事件上建立的。
  3. 考慮添加窗口偵聽器或事件(可以在搜索或Google / Bing中找到的常規SO問題),以在用戶關閉窗口時正確結束程序。

暫無
暫無

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

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