通过JDBC从文本文件大批量 高效的导入mysql数据库操作

import java.io.File;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class LoadTxtData {
private static String filePath = "文件群所在路径";
private static String tableName = "数据库表名";

public static void main(String[] args){
File filelist = new File(filePath);
for (File file : filelist.listFiles()) {
if (!file.isFile()) {
continue;
}
boolean result = loadDataInfile(filePath+"/"+file.getName(),tableName);
if(result){
System.out.println("文件数据导入成功!");
}
}
}

public static boolean loadDataInfile(String fileUrl, String table) {
String sql = "load data local infile '" + fileUrl + "' ignore into table " + table + "(列名,...,...);";
String url="jdbc:mysql://数据库ip:端口号/数据库名称?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8";
String userName = "用户名";
String password = "密码";
java.sql.Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
Statement stmt = conn.createStatement();
long a = System.currentTimeMillis();
boolean result = stmt.execute(sql);

System.out.println("sql:" + sql);
long b = System.currentTimeMillis();
System.out.println("time:" + (b - a) + "ms");
return result;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}


return false;
}


}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页