首页 > 解决方案 > 将项目添加到数据库中

问题描述

我想将数据添加到我的数据库中,但我经常遇到错误,我无法在线找到解决我的问题的方法。

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;
import java.sql.*;

public class vrachtwagentoevoegencontroller {
    public Button backbtn;
    public Button toevoegbtn;
    public TextField txtmodel;
    public TextField txtinhoud;
    public TextField txtaantal;

    public vrachtwagentoevoegencontroller() throws SQLException {
    }


    public void back(ActionEvent actionEvent) throws IOException {
        Parent root2 = FXMLLoader.load(getClass().getResource("VrachtwagenBeheer.fxml"));
        Stage stage1 = new Stage();
        stage1.setTitle("Vrachtwagen Beheer");
        stage1.setScene(new Scene(root2));
        stage1.show();
        Stage stage = (Stage) backbtn.getScene().getWindow();
        stage.close();
    }

    Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/dorb_logistics", "root", "jorisDJ1");
    PreparedStatement preparedStatement = null;
    int rs = 0;

    public void add(ActionEvent actionEvent) {
        String model = txtmodel.getText();
        String inhoud = txtinhoud.getText();
        String aantal = txtaantal.getText();

        String sql = "INSERT INTO vrachtwagens (Model, Inhoud, Aantal) VALUES ('"+model+"' and '"+inhoud+"' and '"+aantal+"');";



        try {
            preparedStatement = con.prepareStatement(sql);
            rs = preparedStatement.executeUpdate(sql);
            txtmodel.setText("");
            txtinhoud.setText("");
            txtaantal.setText("");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

这是我到目前为止所拥有的,每次我尝试使用 executeUpdate 它都希望我使用一个 int,但是当我这样做时,它说列行数与 1 的值或类似的值不匹配。有人可以帮我解决这个问题吗?这是错误:java.sql.SQLException:列计数与第 1 行的值计数不匹配

标签: javajavafx

解决方案


首先,您的查询未正确编写。插入查询中的值以逗号分隔:

String sql = "INSERT INTO vrachtwagens (Model, Inhoud, Aantal) VALUES ('"+model+"', '"+inhoud+"', '"+aantal+"');";

然后,您需要PreparedStatement正确使用,而无需将查询传递给executeUpdate. 或者你只是使用一个Statement.

preparedStatement.executeUpdate();

而且由于您正在“使用” a PreparedStatement,因此您实际上不应该连接值,而是使用参数并安全地设置值并防止 SQL 注入。

String sql = "INSERT INTO vrachtwagens (Model, Inhoud, Aantal) VALUES (?, ?, ?);";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, model);
ps.setString(2, inhoud);
ps.setString(3, aantal);

ps.executeUpdate();

推荐阅读