使用查询将CSV数据插入MYSQL数据库

时间:2017-06-01 13:15:31

标签: java mysql csv

我有一个将CSV文件加载到DB的查询  LOAD DATA LOCAL INFILE 'E:/GPA/IT2.csv' INTO TABLE gpatest.semesterone FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'

当我在查询浏览器中执行时,我的查询效果很好但是当我在java中实现它时它不起作用。我已经附上了我的代码,请指导我必要的修改。 `

      String myDriver = "com.mysql.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost:3307/gpatest";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "root");
      String query = "LOAD DATA LOCAL INFILE 'E:/GPA/IT2.csv' INTO TABLE gpatest.semesterone FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';";

      Statement st = conn.createStatement();

      ResultSet rs =  st.executeQuery(query); 
      st.close();
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }

`

1 个答案:

答案 0 :(得分:1)

在查询中使用\\n代替\n

String query = "LOAD DATA LOCAL INFILE 'E:/GPA/IT2.csv' INTO TABLE gpatest.semesterone FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n';";

解释是,\n中的String表示"新行",如果您想要文字" \ n"你必须用另一个反斜杠(这是java String中的转义字符)来反转反斜杠