Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Все ли верно Джава соединение с бд и вывод

Даша Знаток (329), на голосовании 10 месяцев назад
package com.example.demo;

import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.CornerRadii;
import javafx.scene.paint.Color;

import java.io.File;
import java.net.MalformedURLException;
import java.sql.*;

import java.util.ArrayList;

//import com.example.demo.Tools.ProductListMetaData;
import javafx.scene.image.Image;
import javafx.scene.layout.BackgroundFill;


public class DB {
private final String Host="192.168.13.100";
private final String Post="3306";
private final String DbName="user47";
private final String Login="user47";
private final String Password="95157";

private Connection DBconn=null;
private Connection getDBconn() throws SQLException, ClassNotFoundException{
String connStr= "jdbc:mysql://" + Host + ":" + Post + "/" + DbName + "?characterEncoding=UTF8";
Class.forName("com.mysql.cj.jdbc.Driver");
DBconn=DriverManager.getConnection(connStr, Login, Password);
return DBconn;
}

public ArrayList<AnchorPane> getProduct() throws SQLException, ClassNotFoundException{
String Sql = "Select * from Tovar";
try{
Statement statement= getDBconn().createStatement();
ResultSet resultSet = statement.executeQuery(Sql);
ArrayList<AnchorPane> product = new ArrayList<>();
while (resultSet.next()){
AnchorPane hBox = new AnchorPane();
Background background= new Background(new BackgroundFill(Color.LIGHTGRAY, CornerRadii.EMPTY, Insets.EMPTY));
String path = resultSet.getString("Kartinka");
File file=new File(path);
System.out.println(path);
String xz=file.toURL().toString();
Image image =new Image(xz);
ImageView imageView=new ImageView(image);
imageView.setFitHeight(100);
imageView.setFitWidth(100);
imageView.setLayoutX(10);
imageView.setLayoutY(10);
// ProductListMetaData productListMetaData = new ProductListMetaData();
// productListMetaData.setName(resultSet.getString("ProductName"));
// hBox.setUserData(productListMetaData);
Label nameLabel = new Label(resultSet.getString("Tovarnaim"));
nameLabel.setLayoutX(130);
nameLabel.setLayoutY(10);
Label descriptionLabel=new Label("Описание товара: "+resultSet.getString("Opis"));
descriptionLabel.setLayoutX(130);
descriptionLabel.setLayoutY(25);
// if (resultSet.getString("ProductQuantyInStock").equals("0")){
// hBox.setBackground(background);
// }
hBox.getChildren().add(imageView);
hBox.getChildren().add(nameLabel);
hBox.getChildren().add(descriptionLabel);
product.add(hBox);
}
return product;
}catch(SQLException e) {
throw new RuntimeException(e);
}catch (ClassNotFoundException e){
throw new RuntimeException(e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}

}

}
Голосование за лучший ответ
Светлана Скворцова Знаток (258) 11 месяцев назад
package com.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.layout.AnchorPane;
import java.sql.*;
import java.util.ArrayList;

public class Controller {

@FXML
private ListView<AnchorPane> product;

DB db = new DB();
ArrayList<AnchorPane> ls = null;

@FXML
void initialize() throws SQLException, ClassNotFoundException {
product.getItems().clear();
ls = db.getProduct();
product.getItems().addAll(ls);
}

}
Светлана СкворцоваЗнаток (258) 11 месяцев назад
sort.getItems() .addAll("По возрастанию", "По убыванию", "По умолчанию") ;
sort.setOnAction(event -> {
String selectedOption = sort.getvalue;
product.getItems).clear();
if (selectedOption.equals("По возрастанию")) {
ArrayList<AnchorPane> sortedlist = null;
try {
sortedlist = db.getProductSortASCO;
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
product.getItems).addAll(sortedlist);
} else if (selectedOption.equals("По убыванию")) {
ArrayList<AnchorPane> sortedlist = null;
try {
sortedlist = db.getProductSortDESCO;
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
product.getItems).addAll(sortedlist);
}
Светлана СкворцоваЗнаток (258) 11 месяцев назад
public ArrayList<AnchorPane> getProduct() throws SQLException, ClassNotFoundException{
String Sql = "Select * from Product";
try {
Statement statement = getDbConnection().createStatement();
ResultSet resultSet = statement.executeQuery(Sql);
ArrayList<AnchorPane> product = new ArrayList<>();
while ( resultSet.next ()){
AnchorPane hBox = new AnchorPane();
Background background = new Background(new BackgroundFill(Color.LIGHTGRAY, CornerRadii.EMPTY, Insets.EMPTY));
String path =resultSet.getString("ProductPhoto");
Image image = new Image(path);
ImageView imageView = new ImageView(image);
imageView.setFitHeight(100);
imageView.setFitWidth(100);
imageView.setLayoutX(10);
imageView.setLayoutY(10);
Светлана СкворцоваЗнаток (258) 11 месяцев назад
ProductListMetaData productListMetaData = new ProductListMetaData();
productListMetaData.setName(resultSet.getString("ProductName"));
hBox.setUserData(productListMetaData);
Label nameLabel = new Label(resultSet.getString("ProductName"));
nameLabel.setLayoutX(130);
nameLabel.setLayoutY(10);
Label descriptionLabel = new Label("Описание товара: "+resultSet.getString("ProductDescription"));
descriptionLabel.setLayoutX(130);
descriptionLabel.setLayoutY(25);
if (resultSet.getString("ProductQuantityInStock").equals("0")){
hBox.setBackground(background);
}
hBox.getChildren().add(imageView);
hBox.getChildren().add(nameLabel);
hBox.getChildren().add(descriptionLabel);
hBox.getChildren().add(manufacturerLabel);
hBox.getChildren().add(priceLabel);
Светлана СкворцоваЗнаток (258) 11 месяцев назад
hBox.getChildren().add(countLabel);
product.add(hBox);
}
return product;
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
Светлана СкворцоваЗнаток (258) 11 месяцев назад
в controller
void initialize() throws SQLException, ClassNotFoundException {
Label fio = new Label();
fio.setLayoutX(532);
fio.setLayoutY(14);
fio.setFont(Font.font("Comic Sans MS",14));
fio.setText(dataExchanger.getFio());
pane.getChildren().add(fio);
if (fio.getText()==null){
}else if(fio.getText().contains("Администратор")){
but.setVisible(true);
}

product.getItems().clear();
ls = db.getProduct();
product.getItems().addAll(ls);
Светлана СкворцоваЗнаток (258) 11 месяцев назад
controller
@FXML
private void onclick() throws IOException {
dataExchanger.setFio("");
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("Authorization.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(fxmlLoader.load(),423, 264);
stage.setTitle("Вход");
stage.setScene(scene);
stage.show();
Stage stages = (Stage) product.getScene().getWindow();
stages.close();
}
Светлана СкворцоваЗнаток (258) 11 месяцев назад
controller
@FXML
private void addproduct() throws IOException, SQLException, ClassNotFoundException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("AddProduct.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(fxmlLoader.load(),483, 714);
stage.setTitle("Добавление товара");
stage.setScene(scene);
stage.show();
//Stage stages = (Stage) product.getScene().getWindow();
AddProductController addProductController = fxmlLoader.getController();
NewProdList newProdList = new NewProdList() {
@Override
public void onUserAdded(ArrayList<AnchorPane> prod) {
product.getItems().clear();
product.getItems().addAll(prod);
}
};
Светлана СкворцоваЗнаток (258) 5 месяцев назад
ПКДБ
package com.example.demodemodemo;
import java.sql.*;
import java.util.ArrayList;
public class DB {
private final String host = "127.0.0.1";
private final String port = "3306";
private final String db_name = "shop5";
private final String login = "root";
private final String password = "";
Connection dbConn = null;
Connection getDbConn() throws ClassNotFoundException, SQLException {
String strConn = "jdbc:mysql://"+ host +":" +port+"/"+db_name+"?characterEncoding=UTF8";
Class.forName("com.mysql.cj.jdbc.Driver");
dbConn = DriverManager.getConnection(strConn,login,password);
return dbConn;
}
Светлана СкворцоваЗнаток (258) 5 месяцев назад
ПКДБ
String[] getUser(String log, String pass) throws SQLException, ClassNotFoundException {
String sql = "SELECT * FROM users WHERE login_us = ? and password_us = ?";
PreparedStatement statement = getDbConn().prepareStatement(sql);
statement.setString(1,log);
statement.setString(2,pass);
ResultSet res = statement.executeQuery();
while ( res.next ()){
return new String[]{
res.getString("id_role"),
res.getString("fio")
};
}
return new String[2];
}
Светлана СкворцоваЗнаток (258) 5 месяцев назад
ПКДБ
ArrayList<String> getTovar() throws SQLException, ClassNotFoundException {
String sql = "SELECT * FROM `products`";
Statement statement = getDbConn().createStatement();
ResultSet res = statement.executeQuery(sql);
ArrayList<String> name = new ArrayList<>();
while ( res.next ()){
String row = "Название: "+res.getString("title")+" Стоимость: "+ res.getString("price");
name.add(row);
}
return name;
}
}
Светлана СкворцоваЗнаток (258) 5 месяцев назад
ПИ


РП

Александр Искусственный Интеллект (301602) 11 месяцев назад
если работает, то верно
если не работает, то неверно
логично?
ДашаЗнаток (329) 11 месяцев назад
String sql1="SELECT * FROM Service where Discount>=0 and Discount<5";
SELECT `UserSurname`,`UserName`,`UserPatronymic`,Role.RoleName FROM Users JOIN Role ON UserRole=Role.RoleID;
ДашаЗнаток (329) 11 месяцев назад
@FXML
private ComboBox<String> sort;
/
else {
ArrayList<AnchorPane> sortedList = null;
try {
sortedList = db.getProduct();
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
product.getItems().addAll(sortedList);
}
});
}
Похожие вопросы