I'm writing a one-time Java program to add a bunch of rows in a CSV file to a MySQL database. Are there any Java classes/toolkits to help with this? Something that will escape necessary characters, etc? (eg prepared statements)
Or should I just write the statements myself, like this:
result += String.format(
"INSERT INTO node (type, language, title) VALUES (%s, %s, %s)",
node.get("type"), node.get("language"), node.get("title")
);
You might want to check out DbUnit. It has a bunch of tools for manipulating databases from XML and flat files.
If you're using JDBC, use a PreparedStatement. This class will save you the trouble of escaping your inputs manually.
The code will look basically like this (totally from memory -- hope I didn't overlook something):
See this section in the tutorial on Using Prepared Statements:
Oddly this tutorial doesn't seem to mention that using a PreparedStatement also gives you the benefit of having special characters automatically escaped, that it helps prevent SQL injection, etc. - but those are the main benefits.
This might be considered a bit of a sledgehammer approach, but you might want to considering using spring for your SQL calls, then the above becomes as simple as:
This has the advantage of using JDBC prepared statments under the hood, so you won't end up in trouble if the title includes quotes or other characters that would otherwise have to be escaped, while letting Spring handle all the connection, prepared statement and transaction (if needed at all) complexity.
For more see: SimpleJdbcTemplate from the Spring Framework