此代码解决上一个文章遇到的异常
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
/**
* @author wangxin
* @create 2020/10/30 - 10:00
*/
public class MainToMySQL {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String url = "jdbc:mysql://localhost:3306/taxi_test?useUnicode=true&useSSL=false&serverTimezone=UTC&autoReconnect=true&rewriteBatchedStatements=true";
String user = "root";
System.out.println("请输入数据库密码");
String password = scanner.next();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rt = null;
String s5 = null;
//数据表字段
String taxi_ID = null;
String Time = null;
String Y = null;
String X = null;
int count = 1;
/**
* 链接数据库
*/
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
String sql = "INSERT INTO taxi_test(taxi_ID,Time,Y,X) VALUES(?,?,?,?)";
pstm = conn.prepareStatement(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Long startTime = System.currentTimeMillis();
/**
* 处理 数据
*/
System.out.println("请输入文件路径+文件名");
String fileName = scanner.next();
//按行读取字符串
try {
FileReader fr = null;
fr = new FileReader(fileName);
BufferedReader bf = new BufferedReader(fr);
String s;
while ((s = bf.readLine()) != null) {
// System.out.println(s);
String s1 = s.replace("POINT(", "");
String s2 = s1.replace(")", "");
//获取最后一个空格出现的索引
int i = s2.lastIndexOf(" ");
//获取第一个小数点出现的位置
int j = s2.indexOf(".");
//获取第一个;出现的位置。
int k = s2.indexOf(";");
//获取第二个;出现的位置
int end = s2.indexOf(";", k + 1);
//将String --> StringBuffer
StringBuffer sb = new StringBuffer(s2);
//将最后一个空格的位置改为;
StringBuffer s3 = sb.replace(i, i + 1, ";");
// System.out.println(s3);
//将第一个小数点后面数字去掉
//s4 处理的结果156;2014-02-01 00:00:00;41.8836718276551;12.4877775603346
try {
StringBuffer s4 = s3.replace(j, end, "");
s5 = s4.toString();
String[] result = s5.split(";");
// System.out.println(result[0]);
taxi_ID = result[0];
Time = result[1];
Y = result[2];
X = result[3];
pstm.setString(1, taxi_ID);
pstm.setString(2, Time);
pstm.setString(3, Y);
pstm.setString(4, X);
pstm.addBatch();
System.out.println(count++);
pstm.executeBatch();
} catch (Exception e) {
e.printStackTrace();
System.out.println("异常数据行号:" + count);
System.out.println(s);
}
}
Long endTime = System.currentTimeMillis();
System.out.println("OK,用时:" + (endTime - startTime));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
}
此代码还有待优化,没有实现批量导入数据库,导致数据导入数据库速度太慢