Нужна помощь в заполнении данных в таблицу из БД с использованием javaFX - PullRequest
0 голосов
/ 07 января 2020

Я работаю над школьным проектом и все еще очень начинаю с Java. Я пытаюсь получить данные из БД в таблицу. Каждый раз, когда я пытаюсь что-то сломать. Мой код наверняка небрежный. Мне весело учиться, но я продолжаю застрять.

Вот мои java файлы, которые я создал.

MainApp. java

package pickadate;
import com.mysql.jdbc.Connection;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import pickadate.model.Customer;
import pickadate.model.User;
import pickadate.util.DBConnect;
import pickadate.view.NewCustomerScreenController;
import java.io.IOException;
import static pickadate.util.DBConnect.closeConn;

public class MainDateApp extends Application {

@Override
    public void start(Stage primaryStage) throws Exception {


        Parent loginScreen = FXMLLoader.load(getClass().getResource("/pickadate/view/LoginScreen.fxml"));
        primaryStage.setTitle("Pick A Date");
        primaryStage.setScene(new Scene(loginScreen));
        primaryStage.show();
    }

    public static void main (String[]args)
    {
        DBConnect.init();
        Connection connDB = DBConnect.getConn();
        launch(args);
        closeConn();

    }

    public void showPersonOverview() {

        try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainDateApp.class.getResource("view/NewCustomerScreen.fxml"));
            AnchorPane newCustomerScreenController = loader.load();

            NewCustomerScreenController controller = loader.getController();
            controller.setMainDateApp(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Это мой класс контроллера.

package pickadate.view;
import com.sun.rowset.internal.Row;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import pickadate.MainDateApp;
import pickadate.model.City;
import pickadate.model.Customer;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NewCustomerScreenController implements Initializable {

    //Table and columns
    @FXML
    private TableView<Customer> customerTableView;
    @FXML
    private TableColumn<Customer, String> nameColumn;
    @FXML
    private TableColumn<Customer, String> phoneColumn;

    // Instance variables used to create new person
    @FXML
    private TextField customerId;
    @FXML
    private TextField nameTextField;
    @FXML
    private TextField addressTextField;
    @FXML
    private TextField addressTwoTextField;
    @FXML
    private ComboBox<City> cityComBox;
    @FXML
    private TextField countryTextField;
    @FXML
    private TextField postalTextField;
    @FXML
    private TextField phoneTextField;

    //Buttons
    @FXML
    private ButtonBar newEdDelButtonBar;
    @FXML
    private ButtonBar saveCancelButtonBar;

    // Connects to Main Date App
    private MainDateApp mainDateApp;

    //Constructor called before initialize() method
    public NewCustomerScreenController() {
    }


    //Method to create a new person object and add to the table
   public void saveCustomerButtonPushed() {
       Customer newCustomer = new Customer(nameTextField.getText(),
               addressTextField.getText(),
               addressTwoTextField.getText(),
               cityComBox.getValue(),
               countryTextField.getText(),
               postalTextField.getText(),
               phoneTextField.getText());

       //Get all items from the table as a list then add new customer to list.
       customerTableView.getItems().add(newCustomer);
   }

    // New button will clear text fields
    public void newButtonPushed() {
        nameTextField.setText(null);
        addressTextField.setText(null);
        addressTwoTextField.setText(null);
        countryTextField.setText(null);
        postalTextField.setText(null);
        phoneTextField.setText(null);
    }

     /**
     * Is called by the main application to give a reference back to itself.
     *
     * @param mainDateApp
     */

    public void setMainDateApp(MainDateApp mainDateApp) {
        this.mainDateApp = mainDateApp;


        nameColumn.setCellValueFactory(new PropertyValueFactory<>("customerName"));
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));

    }


    //Section for DB to table
    @Override
    public void initialize(URL location, ResourceBundle resources) {

        ObservableList<Customer> customerNameList = FXCollections.observableArrayList();

        ResultSet rs = accessDB();
        nameColumn.setCellValueFactory(cellData -> cellData.getValue().getCustomerName());
        phoneColumn.setCellValueFactory(cellData -> cellData.getValue().getPhone());

        try {
            rs.beforeFirst(); //this is needed because the result set was looped through in accessDB.  We need to reset the cursor!
            while (rs.next()) {
                String customerName = rs.getString("customerName"); //parameter is the column name in the database
                String phone = rs.getString("phone");

                Customer tr = new Customer(new ReadOnlyStringWrapper(customerName),
                        new ReadOnlyStringWrapper(phone));

                customerNameList.add(tr);

            }
            customerTableView.setItems(customerNameList);
        } catch (SQLException ex) {
            Logger.getLogger(NewCustomerScreenController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ResultSet accessDB() {
            final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
            final String DB_URL = "jdbc:mysql://3.227.166.251:3306/U04s4b";

            //DB Credits
            final String DBUSER = "U04s4b";
            final String DBPASS = "53688332557";

            Connection connDB;
            boolean res = false;
            ResultSet rs = null;

            try {
                Class.forName("com.mysql.jdbc.Driver");

                System.out.println("Connecting to DB...");
                connDB = DriverManager.getConnection(DB_URL, DBUSER, DBPASS);

                Statement stmt;

                try {
                    stmt = connDB.createStatement();
                    rs = stmt.executeQuery("SELECT customer.customerId, customer.customerName, address.address, address.address2, address.postalCode, city.cityId, city.city, country.country, address.phone " +
                            "FROM customer, address, city, country " +
                            "WHERE customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId " +
                            "ORDER BY customer.customerName");

                    while (rs.next()) {
                        System.out.println(rs.getString(1));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
            return rs;
        }



    // End section for DB to table

}

Надеюсь, этого достаточно. Спасибо

...