gpt4 book ai didi

java - 记录未保存在 mysql DB 中

转载 作者:行者123 更新时间:2023-11-29 09:45:32 25 4
gpt4 key购买 nike

我正在开发 logIn 和 singUp 桌面应用程序,但 mySQL 出现问题。记录没有保存在我的表中。这是我的代码:

Connection dbConnection;
public Connection getConnection() throws ClassNotFoundException,
SQLException
{
String connectionString = "jdbc:mysql://" + dbHost + ":"
+ dbPort + "/"
+ dbName;

Class.forName("com.mysql.cj.jdbc.Driver");

dbConnection = DriverManager.getConnection(connectionString + "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", dbUser, dbPass);


return dbConnection;
}
public void signUpSave(User user)
{
String insert = "INSERT INTO " + ConstData.LOGIN_TABLE + " (" +
ConstData.USER_NAME + "," + ConstData.USER_SURNAME + ","
+ ConstData.USER_LOGIN + "," + ConstData.USER_PASSWORD + ","
+ ConstData.USER_EMAIL + ") " + "VALUES(?,?,?,?,?)";
try{
PreparedStatement preparedStatement =
getConnection().prepareStatement(insert);

preparedStatement.setString(1,user.getUserName());
preparedStatement.setString(2,user.getUserSurname());
preparedStatement.setString(3,user.getUserLogin());
preparedStatement.setString(4,user.getUserPassword());
preparedStatement.setString(5,user.getUserEmail());



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

这些是我在上面代码中使用的字符串

protected String dbHost = "localhost";
protected String dbPort = "3306";
protected String dbUser = "root";
protected String dbPass = "root";
protected String dbName = "login";

有一个方法可以从文本字段中获取所有字符串

private void createUser()
{
DataBase dataBase = new DataBase();

String name = nameField.getText();
String lastName = surField.getText();
String userLogin = logField.getText();
String userPswd = pswField.getText();
String userMail = mailField.getText();

User user = new User(name, lastName, userLogin, userPswd, userMail);

dataBase.signUpSave(user);
}

用户类只是一个具有 5 个字符串、构造函数、5 个 getter&setter 的类。

最佳答案

您需要针对基础数据库显式执行准备好的语句。例如:

  final int updatedRowCount = preparedStatement.executeUpdate(); // execute the update
System.out.println("Updated rows: " + updatedRowCount);

关于java - 记录未保存在 mysql DB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55767813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com