如何使用预准备语句插入MD5(“value”+ CURRENT_TIMESTAMP)?

时间:2013-10-07 22:10:09

标签: java mysql prepared-statement md5 sql-insert

我这样做:

String columns = "UserHash,EMail,Name,Gender,BirthYear,Birthday,MaritalStatus,UserID,ReferralUser,Likes";

String sql = "INSERT INTO Users ("+ columns+") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        byte[] bytesOfUserHash = user.getId().getBytes("UTF-8");

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] userHash = md.digest(bytesOfUserHash);

        stmt  = con.prepareStatement(sql);
        stmt.setBytes(1,userHash);
        stmt.setString(2, user.getEmail());
        stmt.setString(3, user.getName());
        stmt.setInt(4, user.getGender().value());
        stmt.setString(5, birthday.split("-")[0]);
        stmt.setString(6, birthday);
        stmt.setInt(7, user.getRelationshipStatus().value());
        stmt.setString(8, user.getId());
        stmt.setString(9, referraluser);
        stmt.setString(10, likesjson);
        stmt.executeUpdate();

除了userHash之外,正在插入所有值,因此查询成功。我该怎么检查?

另外,请注意我现在只是对用户ID进行哈希处理,但我想对用户ID + CURRENT_TIMESTAMP进行哈希处理。

更新 作为一个完整性检查,我只是尝试将一个字符串扔到UserHash列中,因为它是VARCHAR(45)类型,并且它也不起作用。显然有些东西与MD5问题无关。

1 个答案:

答案 0 :(得分:0)

您可以使用MySQL内置的MD5功能,只将userId作为参数传递

    String sql = "INSERT INTO Users ("+ columns+") VALUES (MD5(CONCAT(?,CURRENT_TIMESTAMP), ?, ?, ?, ?, ?, ?, ?, ?, ?);";

    stmt  = con.prepareStatement(sql);
    stmt.setInt(1,user.getId());
    ...