Хотелось бы, чтобы некоторые указатели на приведенный ниже код пытались создать программу, которая извлекает данные из созданной таблицы базы данных City, которая была создана.
Хотите знать, как поместить предварительно заполненные операторы select в текстовую область запроса, которую я могу выбрать, и отправить вместо того, чтобы записывать его и в области результатов, я хотел бы отделить имя и население
РЕДАКТИРОВАТЬ - Добавил SQL поиск и проверил их
РЕДАКТИРОВАТЬ - ДОБАВЛЕНО поле со списком ( необходимо получить оператор SQL в выпадающих списках)
РЕДАКТИРОВАТЬ - Добавлены метки
РЕДАКТИРОВАТЬ --->
Редактировали этот пост, выяснив много новых вещей, добавленных в выпадающий список что go в текстовое поле, но хотел бы выяснить, как заставить их читать односторонним образом, но при нажатии вместо этого вместо реализации оператора SQL я могу отправить ---->, также пытаясь выяснить, как разделить нижнюю часть на название города / население, а затем установить двойное число вместо текущих чисел т выбросил (пример: 12354E7)
package population;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.layout.GridPane;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.scene.control.Button;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import java.sql.*;
import static javafx.application.Application.launch;
import javafx.scene.control.ComboBox;
// What to Create
// 2 lanes seperating city / pop
// Already implanted quries to click and submit
// Sort cities by pop / ascending
//SELECT cityname FROM City ORDER BY population ASC
// Sort cities by pop / descending
//SELECT cityname FROM City ORDER BY population DESC
// Sort cities by name
// SELECT cityname FROM City ORDER BY cityname ASC
// get total pop of all cities
// SELECT SUM(population) FROM city
// get avg pop of all cities
// SELECT AVG(population) FROM city
// get the highest pop
// SQL statement below semi correct
// SELECT population FROM city WHERE population = (select max(population) from city)
// get the lowest pop
// SQL statement below semi correct
// SELECT population FROM city WHERE population = (select min(population) from city)
public class Population extends Application
{
// Database URL.
final String DB_URL = "jdbc:derby:CityDB";
// Controls for input and output
TextArea queryTextArea;
TextArea resultsTextArea;
public static void main(String[] args)
{
// Launch the application
launch(args);
}
@Override
public void start(Stage primaryStage)
{
final int COL_SIZE = 50;
final int ROW_SIZE = 10;
final double SPACING = 10.0;
// Build the query entry area.
Label queryin = new Label("Type Custom Query Here");
queryTextArea = new TextArea();
queryTextArea.setPrefColumnCount(COL_SIZE);
queryTextArea.setPrefRowCount(ROW_SIZE);
// Build the query results area.
Label queryout = new Label("Query Output");
resultsTextArea = new TextArea();
resultsTextArea.setPrefColumnCount(COL_SIZE);
resultsTextArea.setPrefRowCount(ROW_SIZE);
// Create the Submit button.
Button submitButton = new Button("Submit");
submitButton.setOnAction(new SubmitButtonHandler());
// Combobox test????????????????
Label querydroplabel = new Label("Select from drop down");
ComboBox<String> querydrop = new ComboBox<>();
querydrop.getItems().addAll(
"Sort cities by population / acending",
"Sort cities by population / descending",
"Sort cities by name",
"Get total population",
"Get AVG population",
"Get Highest population",
"Get Lowest population");
querydrop.setOnAction(event ->
{
queryTextArea.setText(querydrop.getValue());
});
// Put the controls in a VBox.
VBox vbox = new VBox(SPACING,
querydroplabel,
querydrop,
queryin,
queryTextArea,
submitButton,
queryout,
resultsTextArea);
vbox.setAlignment(Pos.CENTER);
vbox.setPadding(new Insets(SPACING));
// Set the title.
primaryStage.setTitle("Enter a SELECT Query");
// Create a scene and set it to the stage.
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
// Show the stage.
primaryStage.show();
}
/**
* Event handler class for submitButton
*/
class SubmitButtonHandler implements EventHandler<ActionEvent>
{
@Override
public void handle(ActionEvent event)
{
try
{
// Clear the previous results.
resultsTextArea.setText("");
// Create a connection to the database.
Connection conn = DriverManager.getConnection(DB_URL);
// Create a Statement object.
Statement stmt = conn.createStatement();
// Execute the query.
ResultSet resultSet =
stmt.executeQuery(queryTextArea.getText());
// Get the result set meta data.
ResultSetMetaData meta = resultSet.getMetaData();
// Create a string to hold the results
String output = "";
// Get the results.
while (resultSet.next())
{
// Get a row.
for (int i = 1; i <= meta.getColumnCount(); i++)
{
output += resultSet.getString(i);
output += '\t';
}
output += '\n';
}
// Display the results.
resultsTextArea.setText(output);
// Close the statement and the connection.
stmt.close();
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(0);
}
}
}
}