package db.werkzeuge;
import java. io.File; //!!Wrong written because if not WordPress hesitates to save this.
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.sql.*;
class DBLoad {
public static void main (String[] args) {
try {
String startTime = time();
System.out.println("Started at: " + startTime);
String url = "jdbc:oracle:thin:@myserver.ch:12121:STMP01";
Connection conn = DriverManager.getConnection(url,"user1","password1");
int i = 1;
int iSuccess = 0;
for(String stmt : readStatements("in/file_with_update_statements.sql")){
try {
execute(conn, stmt);
iSuccess++;
}catch(Exception e){
System.out.println("ERROR: Could not update row nbr " + i + ". Statement was: " + stmt);
System.out.println(e);
}
i++;
}
System.out.println("\nEND: Updated " + iSuccess + " records on DB.");
System.out.println("Start time: " + startTime + " / " + " Finished at: " + time());
// conn.commit();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
private static List<String> readStatements(String fileName){
File file = new File(DBLoad.class.getClassLoader().getResource(fileName).getFile());
try (Stream<String> stream = Files.lines(file.toPath())) {
return stream.filter(s -> !s.startsWith("--")).map(s -> s.replaceAll(";", "")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return new ArrayList<>();
}
private static void execute(Connection conn, String stmt) throws SQLException {
System.out.print("X");
Statement st = conn.createStatement();
st.executeUpdate(stmt);
}
public static String time() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return dtf.format(now);
}
}
Remark: ‚import java. io.File‚ habe ich absichtlich falsch geschrieben, da sonst WordPress sich weigern würde den Beitrag abzuspeichern. Fehlermeldung: „Aktualisierung fehlgeschlagen. Die Antwort ist keine gültige JSON-Antwort.“
Refernce used: Alvin Alexanders Blog über JDBC …