0
我正在使用Groovy Sql.withBatch来处理CSV文件并在我的Postgres数据库中加载所有数据。Groovy Sql WithBatch在DB中缺少记录
这里我的方法:
def processCSV() {
def logger = Logger.getLogger('groovy.sql')
logger.level = Level.FINE
logger.addHandler(new ConsoleHandler(level: Level.FINE))
def fileName = "file.csv"
def resource = this.getClass().getResource('/csv/' + fileName)
File file = new File(resource.path)
String year = '2016'
char separator = ','
def lines = CSV
.separator(separator)
.skipLines(1)
.quote(CSVParser.DEFAULT_QUOTE_CHARACTER)
.escape(CSVParser.DEFAULT_ESCAPE_CHARACTER)
.charset('UTF-8')
.create()
.reader(file)
.readAll()
def totalLines = lines.size()
Sql sql = getDatabaseInstance()
println("Delete existing rows for " + year + " if exists")
String dQuery = "DELETE FROM table1 WHERE year = ?"
sql.execute(dQuery, [year])
def statement = 'INSERT INTO table1 (column1, column2, column3, coulmn4, year) VALUES (?, ?, ?, ?, ?)'
println("Total lines in the CSV files: " + totalLines)
def batches = []
sql.withBatch(BATCH_SIZE, statement) { ps ->
lines.each { fields ->
String coulmn1 = fields[0]
String coulmn2 = fields[1]
String column3 = fields[2]
String column4 = fields[3]
def params = [column1, coulmn2, column3, column4, year]
def batch = ['params': params, 'error': false]
try {
ps.addBatch(params)
}
catch (all) {
batch['error'] = true
throw all
}
batches << batch
}
}
def recordsAddedInDB = sql.firstRow("SELECT count(*) FROM " + tableName + " WHERE year = ?", year)[0]
sql.close()
println("")
println("Processed lines: " + line)
println("Batches: " + batches.size())
println("Batches in error: " + batches.findAll{ it.error }.size())
println("Record in DB for " + year + ": " + recordsAddedInDB)
}
在CSV文件中的行(exclusing标题行)是23758. 这种方法的输出是下面的:
Delete existing rows for 2016 if exists
Total lines in the CSV files: 23758
Processed lines: 23758
Batches: 23758
Batches in error: 0
Record in DB for 2016 year: 23580
如果启用在日志中,使用BATCH_SIZE为500,我可以看到:
- 47次,句子“成功LY执行批次500命令(多个)”
- 1时间句子‘成功执行批次258命令(多个)’
这意味着23758插入语句已经被处理。
任何人都知道为什么数据库中的行数少于已处理的行数?
只适用于exatra forensics:可能值得看看sql.withBatch的返回值,例如'def counts = sql.withBatch {} .sum()'。在ps.addBatch之后直接添加一个'ps.executeBatch()'也可能很有用,以查看你得到的结果。 –
sql.withBatch {} .sum()返回23580 ...这与我在数据库中的记录数相同。如果我添加了ps.executeBatch(),那么每个插入语句都是单独执行的,sql.withBatch {} .sum()返回0,并且在数据库中我仍然有相同数量的记录。 – Bagbyte
您是否有可能在indata中为id列重复值?即您可能会插入相同的行,它们会在数据库中相互覆盖。 –