记录未保存在mysql DB中

时间:2019-04-19 21:00:33

标签: java mysql javafx jdbc

我正在使用登录和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";

有一种方法可以从textFields中获取所有字符串

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的类。

1 个答案:

答案 0 :(得分:1)

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

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