简体   繁体   中英

java.sql.SQLException: ResultSet is from UPDATE. No Data

I'm trying to import table using Java application. The query runs perfectly with MySQL Workbench:

Here is the query:

LOAD DATA LOCAL INFILE 'C:\\Users\\Zero\\Desktop\\Book1.csv' INTO TABLE  tbl_students
FIELDS TERMINATED BY ',' 
enclosed by '"' 
lines terminated by '\n'

Now using that, I included a save path for the user to locate the file here is the code:

    chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
     FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV Files", "csv");
     chooser.setFileFilter(filter);
    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        path = file.getAbsolutePath();
        System.out.println(path.replace("\\", "\\\\"));
        ImportTBL();

    }
    else {
        System.out.println("No Selection ");}

for the ImportTBL() here is the code

private void ImportTBL(){
    String sql = "LOAD DATA LOCAL INFILE '"+path.replace("\\", "\\\\")+"' INTO TABLE tbl_students "
    + "FIELDS TERMINATED BY ',' enclosed by '\"' lines terminated by '\\n'";
    System.out.println(sql);
    try{PreparedStatement ps = conn.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();

        if(rs.next()){
        JOptionPane.showMessageDialog(null, "Import Successful!");
        }

        else{
        JOptionPane.showMessageDialog(null, "Import Fail!");}
        }

    catch(Exception e){
        JOptionPane.showMessageDialog(null, "Error: "+ e);
        }
}

I think you are using the wrong execute method. The exception you get states that ResultSet is from UPDATE. No Data

Try using:

int affectedRows = ps.executeUpdate();

if ( affectedRows <= 0 ) System.out.println("failed!");
else System.out.println("Success :)");

see: http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeUpdate()

The problem is that you are executing the load statement with executeQuery() method. It is designed for executing select statements that return a resultset, not a data manupulation statement, that does not. Use executeUpdate() method instead and check the number of rows affected to determine if the execution was successful.

Also, there is no need to prepare this statement because it's highly unlikely that the user would run this repeatedly several times right after each other. And you code does not even try to make use of the advantages offered by prepared statements.

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