无法从mysql数据库

时间:2016-08-29 06:43:19

标签: java mysql

我开发了一个Java程序,用于将数据从CSV加载到MySQL,我无法从给定路径中找到CSV文件,我收到错误FileNotFoundException。我添加了程序的代码和日志文件

public class Csvfile {

     public static void main(String[] args) throws Exception{                
            /* Create Connection objects */
            Class.forName ("com.mysql.jdbc.Driver"); 
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/csv","root","admin");
            PreparedStatement sql_statement = null;
            String jdbc_insert_sql = "insert into csvdata"+"(id,age)values"+"(?,?)";

            sql_statement = conn.prepareStatement(jdbc_insert_sql);
            /* Read CSV file in OpenCSV */
            String inputCSVFile = "data1.csv";
            CSVReader reader = new CSVReader(new FileReader(inputCSVFile));
            /* Variables to loop through the CSV File */
            String [] nextLine; /* for every line in the file */            
            int lnNum = 0; /* line number */

             while ((nextLine = reader.readNext()) != null) {
                    lnNum++;
                    /* Bind CSV file input to table columns */
                    sql_statement.setString(1, nextLine[0]);
                    /* Bind Age as double */
                    /* Need to convert string to double here */
                    sql_statement.setDouble(2,Double.parseDouble(nextLine[1]));
                    /* execute the insert statement */
                    sql_statement.executeUpdate();
            }       
             /* Close prepared statement */
            sql_statement.close();
            /* COMMIT transaction */
            conn.commit();
            /* Close connection */
            conn.close();

}
;

日志文件

Exception in thread "main" java.io.FileNotFoundException: data1.csv (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at csvfile.Csvfile.main(Csvfile.java:32)

1 个答案:

答案 0 :(得分:0)

我通过添加csv文件的路径找到了答案

  sql_statement = conn.prepareStatement(jdbc_insert_sql);
            /* Read CSV file in OpenCSV */
            String inputCSVFile = "R:\\java task\\22-8-16\\Csvfile\\src\\csvfile\\data1.csv";
            CSVReader reader = new CSVReader(new FileReader(inputCSVFile));

添加路径后,它可以正常工作