java - 将项目添加到数据库中
问题描述
我想将数据添加到我的数据库中,但我经常遇到错误,我无法在线找到解决我的问题的方法。
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 行的值计数不匹配
解决方案
首先,您的查询未正确编写。插入查询中的值以逗号分隔:
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();
推荐阅读
- flutter - 将数据添加到另一个页面上的列表 Flutter
- apache-flink - Flink 检查点与 kafka 分区有关吗?
- spring - 休眠 | 使用枚举属性转换器映射数据类型“字节”不起作用 - 错误:没有 JDBC 类型的方言映射:277630005
- c# - 将 JsonResponse 反序列化为 C# 对象
- c - C程序在我停止后给出结果
- windows - Win CMD 中的二进制文件编辑
- javascript - 使用 Xpath 唯一标识自动完成列表中具有相似文本的元素
- c# - 如何组织多个动画?需要帮助做一个组合
- c++ - 使用其他类的构造函数时出现链接器错误“未解析的外部符号”
- vb.net - 如何仅制作文本框或组合框,除了三个月名称如果不是 3 个月(1 月 2 月 3 月),任何其他月份输入它应该给出错误