Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Writing SQL Statements

Tags:

java

sql

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")
);
like image 426
Nick Heiner Avatar asked Jan 18 '26 06:01

Nick Heiner


1 Answers

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):

String sql = "INSERT INTO node (type, language, title) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
try
{
    pstmt.setString(1, node.get("type"));
    pstmt.setString(2, node.get("language"));
    pstmt.setString(3, node.get("title"));
    pstmt.executeUpdate();
}
finally
{
    pstmt.close(); 
}
like image 67
Drew Wills Avatar answered Jan 20 '26 20:01

Drew Wills