简体   繁体   中英

Transfer parameter into a preparedStatement from list<String>

I've this preparesStatement:

String insertSQL = "(INSERT INTO visit(Doc_Number, Pat_Number,
               to_timestamp(Date DD/MM/YYYY), Price) VALUES (?,?,?,?))"
PreparedStatement pstvisit = conn.prepareStatement(insertSQL);

And I'm tryind to do this:

for (List<String> row : fileContents){

                pstvisit.clearParameters();
                pstvisit.executeUpdate("INSERT INTO VISIT
                         (Doc_Number, Pat_Number, to_timestamp(Date DD/MM/YYYY), 
                         Price) VALUES (?, ?, ?, ?)");

FileContents read a file data with this format:

# Doc_Nmber, Pat_Number, Visit_Date, Price
26902,6574405,30/03/2011,315
26507,6392432,14/03/2010,322
35356,6574405,15/02/2011,475
35252,9062865,07/07/2011,140

If I do:

System.out.println(row);

I get the same exit as file data.

My question is, how I can transfer the data of datafile into

preparedStatement like

pstvisit.setInt(1, GetTheDoc_NumberOfTheCorrectRow)
pstvisit.setInt(2, GetThePat_NumberOfTheCorrectRow)

etc.

EDIT

how is created fileContents,

I use this instruction in main class:

public Exercise1UpdateOrInsertDataFromFile() {
        super();
        fileUtilities = new FileUtilities();
    }
public static void main(String[] args) {
        Exercise1UpdateOrInsertDataFromFile app = new Exercise1UpdateOrInsertDataFromFile();
        app.run();
    }

    private void run() {

        List<List<String>> fileContents = null;
        try {
            fileContents = fileUtilities.readFileFromClasspath("exercise1.data");
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: File not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("ERROR: I/O error");
            e.printStackTrace();
        }
        if (fileContents == null) {
            return;
        }

And fileUtilites implementation is:

public class FileUtilities {

    /**
     * Reads a comma separated file from the classpath.
     */
    public List<List<String>> readFileFromClasspath(String file)
            throws FileNotFoundException, IOException {
        InputStream is = getClass().getClassLoader().getResourceAsStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        return readFileFromBufferedReader(bufferedReader);
    }

    /**
     * Reads a comma separated file from the filesystem.
     */
    public List<List<String>> readFileFromFilesystem(String file)
            throws FileNotFoundException, IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        return readFileFromBufferedReader(bufferedReader);
    }

    /**
     * Reads a comma separacted file from a Reader.
     * <ul>
     * <li>Lines started with '#' are ignored.</li>
     * <li>Spaces before and after the comma are ignored.</li>
     * <li>Fields can be surrounded by quotes.
     */
    private List<List<String>> readFileFromBufferedReader(
            BufferedReader bufferedReader) throws FileNotFoundException,
            IOException {
        List<List<String>> fileRows = new ArrayList<List<String>>();
        String line = bufferedReader.readLine();
        while (line != null && line.length() > 0) {
            if (line.charAt(0) != '#') {
                List<String> rowValues = new ArrayList<String>();
                String[] tokens = line
                        .split(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                for (String token : tokens) {
                    String processedToken = stripQutoes(token);
                    rowValues.add(processedToken);
                }
                fileRows.add(rowValues);
            }
            line = bufferedReader.readLine();
        }
        bufferedReader.close();
        return fileRows;
    }

    private String stripQutoes(String token) {
        String tokenWithoutSpaces = token.trim();
        if (tokenWithoutSpaces.length() > 0) {
            if (tokenWithoutSpaces.charAt(0) == '"'
                    && tokenWithoutSpaces
                            .charAt(tokenWithoutSpaces.length() - 1) == '"') {
                return tokenWithoutSpaces.substring(1,
                        tokenWithoutSpaces.length() - 1);
            }
        }
        return tokenWithoutSpaces;
    }
}

You can use String#split() to split row into the four chucks. Then convert each String into its desired format.

for (String row : fileContents) {
    pstvisit.clearParameters();

    String[] rowData = row.split(",");

    int docNumber = Integer.valueOf(rowData[0]);
    int patNumber = Integer.valueOf(rowData[1]);
    String date = row[2];
    int price = Integer.valueOf(row[3]);

    pstvisit.setInt(1, docNumber);
    pstvisit.setInt(2, patNumber);
    pstvisit.setString(3, date);
    pstvisit.setInt(4, price);

    pstvisit.executeUpdate();
}

You should also consider putting the entire 'update' loop above into a transaction to improve performance.

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