我正在尝试将大型 csv 数据上传到云 sql
下面是我的 blobe 商店和 csv 加载器代码。
1:-
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobKey = blobs.get("file");
BlobstoreInputStream **is** = new BlobstoreInputStream(new BlobKey(
blobKey.getKeyString()));
比这样调用 csv loader
loader.loadCSV(****is****, "salesstatus", true, req, resp,httpSession.getAttribute("username1").toString());
这是读取带有标题和数据的 csv 文件的代码。 a)标题
String[] headerRow = csvReader.readNext();
String[] headerRow1 =new String[headerRow.length+1];
int size = headerRow.length;
System.out.println(size);
for(int i=0; i<=size; i++){
if(i<size){
headerRow1[i]=headerRow[i];
}else{
headerRow1[i]="UploadedBy";
}
}
b)生成动态查询
String questionmarks = StringUtils.repeat("?,", headerRow1.length);
questionmarks = (String) questionmarks.subSequence(0, questionmarks
.length() - 1);
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
query = query
.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow1, ","));
query = query.replaceFirst(VALUES_REGEX, questionmarks);
log.info( "query----114-"+query);
c)使用批量更新/批量执行命令从.csv文件中读取数据并插入到云sql中
Connection con = null;
PreparedStatement ps = null;
log.info("inside try 131");
con = this.connection;
con.setAutoCommit(false);
ps = con.prepareStatement(query);
if(truncateBeforeLoad) {
log.info("truncate 136");
con.createStatement();
}
final int batchSize = 1000;
int count = 0;
try {
while((nextLine = csvReader.readNext())!=null){
int lastCol= nextLine.length+1;
if (null != nextLine) {
int index = 1;
for (String colValue : nextLine) {
date = colValue; //DateUtil.convertToDate(string);
if (null != date) {
ps.setString(index++, date);
if(lastCol== index){
ps.setString(6, username);
}
} else {
if(lastCol== index){
ps.setString(6, username);
}else{
ps.setString(index++, colValue);
}
}
}
ps.addBatch();
}
if (++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
con.commit();
这里的问题是当我尝试上传 csv 文件时
当我上传超过 86000 条记录的 csv 数据时,即使 csv 数据正在保存到我的应用程序大约 20000 条记录,但在上传文件结束时我的屏幕会变成空白。
当我检查日志时,我得到了类似语句关闭后不允许操作的执行 我的应用程序出现了这种类型的意外错误。当我向我的应用程序上传非常少的数据(大约 50 条记录)时,它工作正常。
我在谷歌搜索然后我得到了这个问题,比如谷歌云 sql 中的每秒查询限制。引用链接- https://developers.google.com/cloud-sql/faq#sizeqps
有人可以帮我解决这个问题吗? 意思是如果问题出在上面,那么我怎样才能增加每秒对谷歌云 sql 的查询。
最佳答案
这里有很多代码,可能会发生很多事情,但我认为您在这种情况下想要做的是在您的代码中获得一些弹性;现在它假定网络连接始终处于打开状态,但实际上可能不是。当您执行 ps.executeBatch()
时,您不检查数据库连接或语句是否打开。
我会做的是:
- 批量读入内存,而不是
ps
。 - 检查数据库连接是否有效(如果没有则重新创建),然后创建
ps
。 - 使用内存中的batch,放入
ps
。 - 检查
ps
是否成功。如果没有抛出异常,则转2重新开始。如果成功,则返回 1 并在下一批中读取。
这样您的应用将更好地处理网络连接问题。
希望这对您有所帮助!
关于csv - 大型 csv 数据上传到谷歌云 sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405778/