0
Groovy Sql.withBatchを使用してCSVファイルを処理し、Postgres DB内のすべてのデータをロードしています。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コマンド(S)23758 insert文が処理された意味258命令(複数可)、 "
と」
データベース内の行の数が処理された行の数より少ない理由は、誰もが知っていますか?
exatra forensicsの場合:sql.withBatchからの戻り値を調べる価値があるかもしれません。例えば、def counts = sql.withBatch {} .sum() 'です。また、ps.addBatchの直後に 'ps.executeBatch()'を追加すると便利です。 –
sql.withBatch {} .sum()は23580を返します。これはデータベースにあるレコードと同じ数です。 ps.executeBatch()を追加すると、各insert文は単独で実行され、sql.withBatch {} .sum()は0を返し、データベースには同じ数のレコードが残っています。 – Bagbyte
あなたのインダクターのID列に重複した値がありますか?つまり、データベース内で互いに上書きする同一の行を挿入している可能性があります。 –