简体   繁体   中英

How to insert byte arrays into SQL via Java?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM