Java: Writing SQL Statements

前端 未结 4 986
旧时难觅i
旧时难觅i 2021-01-20 23:18

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

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 23:44

    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(); 
    }
    

提交回复
热议问题