jdbc批量执行SQL insert 操作
时间:2021-07-01 10:21:17
帮助过:1人阅读
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class ResolvFile {
public static String readFileContent(String filepath) {
ArrayList<String> records = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filepath));
String aRecord;
while((aRecord = br.readLine())!=null){
records.add(aRecord);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<String> recordList = new ArrayList<String>();
for(int i = 0;i<records.size();i++) {
String record = records.get(i);
String[] recArray = minusQuotation(record.split(","));
String recordSql = getRecordSql(recArray);
if (null!=recordSql) {
recordList.add(recordSql);
}
}
batchExecuteSql(recordList);
return null;
}
public static int batchExecuteSql(ArrayList<String> sqlList) {
System.out.println("接下来可以执行SQL语句或保存对象");
System.out.println("========批量执行SQL语句==========");
System.out.println("将所有语句加入到Statment stat中");
for (int i = 0;i<sqlList.size();i++) {
String string = sqlList.get(i);
System.out.println("通过stat.addBatch(sql)来加入语句"+i+": ‘"+string+"‘");
}
System.out.println("通过stat.executeBatch()来执行所有的SQL语句");
System.out.println("========批量执行SQL语句结束==========");
return sqlList.size();
}
public static String getRecordSql(String[] recArray) {
if (null==recArray) {
return null;
}
String recordSql = "insert into tablename (sms,no,time) values(‘"+recArray[0]+"‘,‘"+recArray[2]+"‘,‘"+recArray[5]+"‘)";
return recordSql;
}
public static String[] minusQuotation(String[] recArray) {
for (int i = 0; i < recArray.length; i++) {
String str = recArray[i];
if (null!=str) {
if(str.indexOf( "\"")==0)
str = str.substring(1,str.length());
if(str.lastIndexOf("\"")==(str.length()-1))
str = str.substring(0,str.length()-1);
}
recArray[i] = str;
}
return recArray;
}
public static void main(String[] args) {
String filepath = "E:\\sxySMS\\smstest.txt";
readFileContent(filepath);
}
}
jdbc批量执行SQL insert 操作
标签: