繁体   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