1

So I know this question has been asked a few different places, but I wasn't able to get a solid answer. So, I'm trying to store usernames, ids, salts, and hashes, and so I've just created the account, and I need to insert the data into the database. I thought just do it like this: int newResults = statement.executeUpdate("INSERT INTO data VALUES (1, 'CyanCoding', " + hash + ", " + salt + ")");

Just so you know, everything is good except in the db except hash and salt, and those variables are BINARY(16) in the db and just byte array in the java program.

So, I ran it and I got "You have an error in your SQL syntax" (very helpful). So I looked it up and people in other answers suggested doing it like this: int newResults = statement.executeUpdate("INSERT INTO data VALUES (1, 'CyanCoding', @hash, @salt)");

And that ran fine, but when I checked the values in the database, hash and salt were both null. So, ignoring the fact that I probably used @hash incorrectly, how should I insert my byte arrays into my SQL table?

1 Answer 1

8

Assuming you are doing a typical JDBC update with a prepared statement, your code should look something along these lines:

String query = "INSERT INTO data (col1, col2, col3, col4) ";
query += "VALUES (1, 'CyanCoding', ?, ?)";    // ? are placeholders
PreparedStatement statement = conn.prepareStatement(query);
statement.setBytes(1, hash);
statement.setBytes(2, salt);
statement.executeUpdate();

This assumes that your both your hash and salt exist as byte arrays in your Java code. If the hash is just a string, then use setString instead.

Note that I included the column names in the INSERT statement, which is considered best practice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.