我现在用jdbc程序往mysql插入十万条假数据,其中一种假数据的生成依赖io读取excel文件,再生成随机数拼接而成。
现在报空指针错误,我怀疑是因为假数据还没有生成,io时间长,for循环的赋值程序就进行了。
现在运行个3秒或4秒,就报空指针错误,一次只能插入200条数据,离目标很远。
我添加if语句判断假数据不为空才继续赋值,也不管用。
请问我该怎么控制啊?
public class AddXXXData {
public static int generateNum(int range){
SecureRandom random = new SecureRandom();
return random.nextInt(range+1);
}
public static double generateFloatNum(){
double min = 1.0;
double max = 200.0;
double boundedDouble = min + new Random().nextDouble() * (max - min);
return boundedDouble;
}
public static String generateXXXname(){
StringBuilder xxName = new StringBuilder();
try {
//创建工作簿对象
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream("C:\\xx\\Desktop\\xx.xlsx"));
XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
int maxRow = sheet.getLastRowNum();
SecureRandom random = new SecureRandom();
int i=random.nextInt(maxRow);
XSSFWorkbook xssfWorkbook2 = new XSSFWorkbook(new FileInputStream("C:\\xx\\Desktop\\yy.xlsx"));
XSSFSheet sheet2 = xssfWorkbook2.getSheetAt(0);
int maxRow2 = sheet2.getLastRowNum();
SecureRandom random2 = new SecureRandom();
int j=random2.nextInt(maxRow2);
xxName.append(sheet2.getRow(j-1).getCell(0)).append(sheet.getRow(i-1).getCell(0));
} catch (IOException e) {
e.printStackTrace();
}
return xxName.toString();
}
@Test
public void add(){
long stime = System.currentTimeMillis();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
String url = "jdbc:mysql://xx.xx.xxx.xxx:3306/ss?characterEncoding=utf-8";
String user = "xx";
String password = "xx";
conn = DriverManager.getConnection(url, user, password);
for(int i=0;i<100000;i++){
int id = generateNum(100);
double num = generateFloatNum();
String name = generateXXXname();
if(name!=null){
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String sql = "INSERT INTO tb_xx (info,xx_name,aa_id,xx_picture," +
"price,num,status,bargin,zz_id,payment_count,insurance,free_delivery," +
"yy_id,created_time,updated_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1," ");
ps.setString(2,name);
ps.setInt(3,id);
ps.setString(4," ");
ps.setDouble(5, num);
ps.setInt(6,100);
ps.setInt(7,1);
ps.setDouble(8,10.0);
ps.setInt(9,id);
ps.setInt(10,0);
ps.setString(11," ");
ps.setInt(12,1);
ps.setInt(13,id);
ps.setTimestamp(14,timestamp);
ps.setTimestamp(15,timestamp);
ps.executeUpdate();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
long etime = System.currentTimeMillis();
System.out.printf("执行时长:%d 秒.", (etime - stime)/1000);
}
}