I'm trying to save the ResultSet of a DB query into an ArrayList to be used as an input to write to a file but I run out of memory. There is about 116k rows of data in the table I'm reading. I've tried writing directly to the file inside the readDB() method and it creates a CSV-file of about 3.3 MB. This is my code.
public class Main {
public static void main(String[] args) {
DBAccess dbAccess = new DBAccess();
}
}
The class and method to read the DB.
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DBAccess {
public List<String> readDB() {
String url = "jdbc:Cobol://Dev/Project Files/DatAndCpyFiles";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement())
{
stmt.setFetchSize(10);
Class.forName("com.hxtt.sql.cobol.CobolDriver").newInstance();
String sql = "select * from PROFS";
ResultSet rs = stmt.executeQuery(sql);
List<String> result = new ArrayList<>();
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int iNumCols = resultSetMetaData.getColumnCount();
for (int i = 1; i <= iNumCols; i++) {
result.add(resultSetMetaData.getColumnLabel(i) + ";");
}
String row;
while (rs.next()) {
for (int i = 1; i <= iNumCols; i++) {
row = rs.getString(i);
row = row == null ? " " : row.replaceAll("\u0086", "å");
row = row == null ? " " : row.replaceAll("\u008F", "Å");
row = row == null ? " " : row.replaceAll("\u0084", "ä");
row = row == null ? " " : row.replaceAll("\u008E", "Ä");
row = row == null ? " " : row.replaceAll("\u0094", "ö");
row = row == null ? " " : row.replaceAll("\u0099", "Ö");
row = row == null ? " " : row.replaceAll("\u0081", "ü");
row = row == null ? " " : row.replaceAll("\u009A", "Ü");
row = row == null ? " " : row.replaceAll("\u0082", "é");
row = row == null ? " " : row.replaceAll("\u0090", "É");
result.add(result + row.trim() + ";");
}
}
rs.close();
System.out.println("Returning result");
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return null;
}
}
}
Error message
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:448)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at java.util.AbstractCollection.toString(AbstractCollection.java:462)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at se.spedweb.DBAccess.readDB(DBAccess.java:56)
at se.spedweb.Main.main(Main.java:15)
What other data structure can I for this? Am I using the wrong approach for this? I could just append to a file instead of add to list in the method but I thought it would be cleaner to have writing to file and reading the database in separate classes, maybe this is wrong.
If you run java with the command line option try using -Xmx, you can manually set the size of the heap. Try setting it to -Xmx2048m.
Note: there's ways to do it if your using an IDE, a quick google will show you how to change it
Related
Alright so I need help in reviewing my codes because I'm kinda still new in programming (currently in my second year of Diploma in Computer Science). I got this error as in the title GC Overhead Limit Exceeded when I tried running my code below.
A brief explanation of this code, I'm trying to read data from a CSV File and then transfer it to a database. FYI, there are actually 10 tables/CSV files that I need to read, but on this I'll show this one table Tickets because the error only occurred when I tried to read that table/file. The other tables have hundreds of rows/data only while the table Tickets have 735,504 of rows/data. Furthermore, I've succeeded in reading 450,028 of data after 6 hours of running the code before the error occurred.
What can I do to fix this error? What can be modified to improve my code? I really appreciate it if you guys can help me :)
public class Demo2 {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database";
String username = "root";
String password = "password";
try {
//Connect to the database
Connection connection = DriverManager.getConnection(url, username, password);
//Test on one table only
String tableName = "Tickets";
System.out.println("Connecting to TABLE " +tableName +"...");
readCSVFile(tableName, connection);
System.out.println();
System.out.println("THE END");
connection.close();//close connection to the database
}
catch (SQLException e) {
System.out.println("ERROR at main(): SQLException!!");
e.printStackTrace();
}
}
static int countNewRow = 0;
static int countUpdatedRow = 0;
//Method to read the CSV File
static void readCSVFile(String tableName, Connection conn) {
//Read CSV File
try {
String path = tableName +".csv";
BufferedReader br = new BufferedReader(new FileReader(path));
br.readLine();//skip the first line
String inData;
//Read The Remaining Line
while((inData=br.readLine()) != null)
{
String[] rowData = inData.split(",");
ArrayList <String> rowDataList = new ArrayList<String>();
for (int i=0; i<rowData.length; i++)
rowDataList.add(rowData[i]);
//To combine String that starts and ends with "
for(int i=0; i<rowDataList.size(); i++) {
if (rowDataList.get(i).charAt(0) == '"') {
String string1 = rowDataList.get(i).substring(1, rowDataList.get(i).length());
String string2 = rowDataList.get(i+1).substring(0, rowDataList.get(i+1).length()-1);
String combined = string1 +"," +string2;
rowDataList.set(i, combined);
rowDataList.remove(i+1);
break;
}
}
//Remove the RM
for(int i=0; i<rowDataList.size(); i++) {
if (rowDataList.get(i).startsWith("RM")) {
String string = rowDataList.get(i).substring(2);
rowDataList.set(i, string);
}
}
//This is just to keep track of the data that has been read
System.out.println("[" +rowDataList.get(0) +"]");
//Transfer the data to the database
insertToDatabase(conn, tableName, rowDataList);
}
System.out.println("New Row Added : " +countNewRow);
System.out.println("Updated Row : " +countUpdatedRow);
System.out.println("== Process Completed ==");
br.close();
}
catch (FileNotFoundException e) {
System.out.println("ERROR at readCSVFile(): FileNotFoundException!!");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("ERROR at readCSVFile(): IOException!!");
e.printStackTrace();
}
catch (SQLException e) {
System.out.println("ERROR at readCSVFile(): SQLException!!");
e.printStackTrace();
}
catch (ParseException e) {
System.out.println("ERROR at readCSVFile(): ParseException!!");
e.printStackTrace();
}
}
static void insertToDatabase(Connection connection, String tableName, ArrayList <String> rowDataList) throws SQLException, ParseException {
String tableIdName = tableName;
if (tableIdName.charAt(tableIdName.length()-1) == 's')
tableIdName = tableIdName.substring(0, tableIdName.length()-1);
//To read row
String rowID = rowDataList.get(0);
String selectSQL = "SELECT * FROM " +tableName +" "
+"WHERE " +tableIdName +"_ID = " +rowID;
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(selectSQL);
boolean value = result.next();
//INSERT # UPDATE row
if (value == true) { //Update Row if the data is already existed
updateStatementt(tableName, connection, rowDataList);
countUpdatedRow++;
}
else { //Insert New Row
insertStatementt(tableName, connection, rowDataList);
countNewRow++;
}
}
//Method to insert data to the database
static void insertStatementt(String tableType, Connection conn, ArrayList <String> rowDataList) throws SQLException, ParseException {
//Generate Question Mark
String generateQuestionMark = null;
if(rowDataList.size() == 1)
generateQuestionMark = "?";
else
generateQuestionMark = "?, ";
for(int i=1; i<rowDataList.size(); i++) {
if(i!=rowDataList.size()-1)
generateQuestionMark += "?, ";
else
generateQuestionMark += "?";
}
//Insert sql
String sql = "INSERT INTO " +tableType +" VALUES (" +generateQuestionMark +")";
PreparedStatement insertStatement = conn.prepareStatement(sql);
//Insert data
//There are other 'if' and 'else if' statements here for other tables
else if (tableType.equals("Tickets")) {
int ticketID = Integer.parseInt(rowDataList.get(0));
int movieId = Integer.parseInt(rowDataList.get(1));
int theaterId = Integer.parseInt(rowDataList.get(2));
String[] date = rowDataList.get(3).split("/");
String dateString = date[2] +"-" +date[1] +"-" +date[0];
Date showDate = Date.valueOf(dateString);
int showTimeId = Integer.parseInt(rowDataList.get(4));
int cptId = Integer.parseInt(rowDataList.get(5));
int pcId = Integer.parseInt(rowDataList.get(6));
float amountPaid = Float.parseFloat(rowDataList.get(7));
int year = Integer.parseInt(rowDataList.get(8));
String month = rowDataList.get(9);
insertStatement.setInt(1, ticketID);
insertStatement.setInt(2, movieId);
insertStatement.setInt(3, theaterId);
insertStatement.setDate(4, showDate);
insertStatement.setInt(5, showTimeId);
insertStatement.setInt(6, cptId);
insertStatement.setInt(7, pcId);
insertStatement.setFloat(8, amountPaid);
insertStatement.setInt(9, year);
insertStatement.setString(10, month);
}
insertStatement.executeUpdate();
insertStatement.close();
}
//Method to update the data from the database
static void updateStatementt(String tableType, Connection conn, ArrayList <String> rowDataList) throws SQLException {
Statement statement = conn.createStatement();
String sql = "UPDATE " +tableType;
//There are other 'if' and 'else if' statements here for other tables
else if (tableType.equals("Tickets")) {
String[] date = rowDataList.get(3).split("/");
String dateString = date[2] +"-" +date[1] +"-" +date[0];
sql += " SET movie_id = " +rowDataList.get(1) +","
+ " theater_id = " +rowDataList.get(2) +","
+ " showdate = \"" +dateString +"\","
+ " showtime_id = " +rowDataList.get(4) +","
+ " costperticket_id = " +rowDataList.get(5) +","
+ " personcategory_id = " +rowDataList.get(6) +","
+ " amount_paid = " +rowDataList.get(7) +","
+ " year = " +rowDataList.get(8) +","
+ " month = \"" +rowDataList.get(9) +"\""
+ " WHERE ticket_id = " +rowDataList.get(0);
}
statement.executeUpdate(sql);
}
}
For short, read a single line and do whatever you want to do with it. You don't have enough memory for all 700k lines.
You should add statement.close() for the update Statement.
If you really want to read all this data into the Java heap, increase the heap size using, for example, the -Xmx command-line switch. Because of the way textual data is encoded in the JVM, you'll probably need much more heap that the total data size would suggest.
In addition, there might be some places in your code where you can take the strain off the JVM's memory management system. For example, concatenating strings using "+" can generate a lot of temporary data, which will increase the load on the garbage collector. Assembling strings using a StringBuilder might be a simple, less resource-hungry, alternative.
I am working on a Java-Jdbc program which will take the row count of all the tables present in the database. To do that, I came up with the following code:
// Get the source(gp) count
public Map<String,Long> getGpTableCount() throws SQLException {
Map<String, String> gpTableMap = getScopeTableList(); // Key: Sourceschema.tablename, value: Destschema.tablename:sourcesystem1,sourcesystem2...sourcesystemn
Set<String> gpTableSet = gpTableMap.keySet(); // Gets the Source Table names - Schema.Tablename
gpCountMap = new HashMap<String, Long>();
Iterator<String> keySetIterator_gpTables = gpTableSet.iterator();
Connection gpAnalyticsCon = (Connection) DbManager.getGpConnection();
while(keySetIterator_gpTables.hasNext()) {
//getting source system names
String gpTabSchemakey = keySetIterator_gpTables.next();
String tablesnSSNs = gpTableMap.get(gpTabSchemakey);
String[] ssnArray = tablesnSSNs.split(":");
String sourceSystems = ssnArray[1];
System.out.println(sourceSystems);
if(sourceSystems.equals("No_SSNs_available") || sourceSystems == "No_SSNs_available") {
System.out.println("In the if condition");
gptableCountWithoutSsn = tblCountWithoutSsn(gpTabSchemakey, gpAnalyticsCon);
gpTabMapWoSsn.put(gpTabSchemakey, gptableCountWithoutSsn);
} else {
System.out.println("In the else condition");
//get the source system names
String inSourceSystems = "('" + sourceSystems.replace(",", "','") + "')";
String gpSchemaTableName = gpTabSchemakey;
String[] gpparts = gpSchemaTableName.split("\\."); // schema, tablename
String gpTable = gpparts[1];
String gpCountQuery = "select '" + gpTable + "' as TableName, count(*) as Count, source_system_name from " + gpSchemaTableName + " where source_system_name in " + inSourceSystems +" group by source_system_name order by source_system_name";
// resultSet(1): TableName, resultSet(2): count, resultSet(3): source_system_name
try {
PreparedStatement gp_pstmnt = gpAnalyticsCon.prepareStatement(gpCountQuery);
ResultSet gpCountRs = gp_pstmnt.executeQuery();
while(gpCountRs.next()) {
System.out.println("Tablename: " + gpCountRs.getString(1) + " Source System Name: " + gpCountRs.getString(3) + ", Count: " + gpCountRs.getLong(2));
System.out.println(" ");
ssn = getSsn(gpCountRs.getString(3));
gpCountMap.put(gpTable + ": " + gpCountRs.getString(3), gpCountRs.getLong(2));
}
} catch(org.postgresql.util.PSQLException e) {
System.out.println("Table: " + gpTable + " not found for the source system: " + ssn);
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
gpAnalyticsCon.close();
return gpCountMap;
}
There are two kinds of tables in the code.
Tables that have source systems
Tables without any source systems
There is an if-else condition where tables without sourcesystem names go to 'if' and those have source systems, go to 'else' condition.
In the 'if', I am calling another method: tblCountWithoutSsn which is written as:
// Method that returns the row count of tables without any source system name
private Long tblCountWithoutSsn(String tableWithoutSsn, Connection con) throws SQLException {
String[] woSsn = tableWithoutSsn.split("\\.");
long count=0;
String tablename = woSsn[1];
String query = "select '" + tablename + "' as TableName, count(*) as count from " + tableWithoutSsn;
System.out.println("Executing table: " + tablename + " which doesn't have any source system name");
System.out.println("Query for tables with no source_systems: " + query);
PreparedStatement gpwoSsn_pstmnt = con.prepareStatement(query);
ResultSet rs = gpwoSsn_pstmnt.executeQuery();
while(rs.next()) {
count = rs.getLong(2);
}
System.out.println("TableName: " + tablename + ", count: " + count);
return count;
}
There are 41 tables without any source systems. When I execute the jar file, I could see the count such of tables:
In the if condition
Executing table: table1withoutSSN which doesn't have any source system name
Query for tables with no source_systems: select 'table1withoutSSN' as TableName, count(*) as count from analytics_view.table1withoutSSN
TableName: table1withoutSSN, count: 1764
In the if condition
Executing table: table2withoutSSN which doesn't have any source system name
Query for tables with no source_systems: select 'table2withoutSSN' as TableName, count(*) as count from ge_hr3.table2withoutSSN
TableName: table2withoutSSN, count: 473376
But as soon as it reaches the table: table3WithoutSSN the code give exception and connection closes. The exception can be seen below:
In the if condition
Executing table: table3WithoutSSN which doesn't have any source system name
Query for tables with no source_systems: select 'table3WithoutSSN' as TableName, count(*) as count from custSchema.table3WithoutSSN
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: org.postgresql.util.PSQLException: This connection has been closed.
at org.postgresql.jdbc.PgConnection.checkClosed(PgConnection.java:803)
at org.postgresql.jdbc.PgConnection.prepareStatement(PgConnection.java:1621)
at org.postgresql.jdbc.PgConnection.prepareStatement(PgConnection.java:415)
at com.recordcount.dao.GpHiveRecords.tblCountWithoutSsn(GpHiveRecords.java:156)
at com.recordcount.dao.GpHiveRecords.getGpTableCount(GpHiveRecords.java:72)
at com.recordcount.entry.StartCount.main(StartCount.java:12)
... 5 more
The line 156 in the exception is:
PreparedStatement gpwoSsn_pstmnt = con.prepareStatement(query); from the method: `tblCountWithoutSsn`
Connection method in DBManager Class:
private static Connection gpAnalyticsConnection = null; // Creating gp connection
public static Connection getGpConnection() {
try {
Class.forName("org.postgresql.Driver");
if(gpAnalyticsConnection == null) {
gpAnalyticsConnection = DriverManager.getConnection("hostname", "username", "password");
return gpAnalyticsConnection;
} else {
return gpAnalyticsConnection;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
Could anyone let me know what is the mistake I am doing here and how can I rectify that.
Getting the results of a SQL query where I want row 5 from every record that is returned.
I would like to export the data to an Excel spreadsheet in rows of thirteen, starting at the second row (I have headers).
My SQL logic is obviously off right now because I'm getting the first result thirteen times in increasing rows and columns, although it is properly starting on the second row and only going out 13 columns. The second result repeats in this fashion, as does each successive result.
I suspect my troubles start at while (rs.next()) {
for (int i = 0; i < 13; i++) {
package process;
import java.util.Scanner;
import java.io.*;
import java.sql.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class Sec_Completions {
public static void main(String[] args) {
Sec_Completions obj_Sec_Completions=new Sec_Completions();
obj_Sec_Completions.Check_Data();
}
public void Check_Data() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the beginning date of completion YYYY/MM/DD");
String doc = scanner.nextLine();
doc = doc + " 00:00";
System.out.println("Date is" + " " + doc);
final String sql = "SELECT DISTINCT wp_grassblade_completions.user_id, wp_grassblade_completions.status, wp_grassblade_completions.content_id, wp_usermeta.meta_key, CASE WHEN meta_value = 'male' THEN 'M' WHEN meta_value = 'female' THEN 'F' WHEN meta_value = 'Louisiana' THEN 'LA' ELSE meta_value END AS '1', wp_usermeta.meta_value, wp_usermeta.user_id, wp_grassblade_completions.timestamp\r\n" +
"FROM wp_grassblade_completions \r\n" +
"INNER JOIN wp_usermeta ON wp_grassblade_completions.user_id = wp_usermeta.user_id\r\n" +
"WHERE wp_grassblade_completions.timestamp >= ? AND meta_key IN ('mepr_full_name', 'mepr_address', 'mepr_city', 'mepr_state', 'mepr_zip_code', 'mepr_home_phone_with_area_code', \r\n" +
" 'mepr_drivers_license_or_id', 'mepr_id_state', 'mepr_LAst_four_of_social_security_number', 'mepr_date_of_birth_mmddyyyy', 'mepr_sex_mf', 'mepr_height', 'mepr_weight') AND content_id IN ('1575, 642, 1580') \r\n" +
"ORDER BY wp_grassblade_completions.timestamp, content_id, wp_usermeta.user_id";
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://wpengine.com:3306/wp_database","user", "passsword");
PreparedStatement ps =null;
ps=connection.prepareStatement(sql);
ps.setString(1, doc);
Statement st = connection.createStatement();
ResultSet rs = ps.executeQuery();
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Security");
XSSFRow rowhead = sheet.createRow((short) 0);
int index = 1;
while (rs.next()) {
for (int i = 0; i < 13; i++) {
XSSFRow row = sheet.createRow((short) index);
row.createCell((short) i).setCellValue(rs.getString(5));
index++;
}
}
FileOutputStream fileOut = new FileOutputStream("D://OneDrive//ABSEC//ATC_Reporting//expdata1.xlsx");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
rs.close();
connection.close();
} catch (Exception e) {
System.out.println(e);
}
Edited, again
Try something like this:
// META_KEY values, in the order that the columns should be. This should be a
// private static final outside of in the class, along with the query's text...
String[] keys = { "mepr_full_name", "mepr_address", "mepr_city", "mepr_state",
"mepr_zip_code", "mepr_home_phone_with_area_code",
"mepr_drivers_license_or_id", "mepr_id_state",
"mepr_LAst_four_of_social_security_number", "mepr_date_of_birth_mmddyyyy",
"mepr_sex_mf", "mepr_height", "mepr_weight" };
// Running thru the ResultSet
short index = 1;
while ( rs.next() )
{
XSSFRow row = sheet.createRow( index );
String key = rs.getString(4); // meta_key
String value = rs.getString( 5 ); // meta_value
for ( short i = 0; i < keys.length; ++i )
{
if ( keys[i].equals( key))
{
// Retrieving cell, creating if not exists
XSSFCell cell = row.getCell( i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK );
// if the cell is used, increment index o get to the next row
if ( cell.getCellTypeEnum() != CellType.BLANK )
++index;
// Set the value
cell.setCellValue( value );
// No need to walk thru the rest of the array...
break;
}
}
}
This only works, tho, if any "next row" does not start with a column that has no value in the previous row...
For this reason you should also add meta_key to the ORDER BY clause...
With some additional cleanup, something like this:
SELECT DISTINCT wpgc.user_id, wpgc.status, wpgc.content_id, wpu.meta_key,
CASE wpu.meta_value WHEN 'male' THEN 'M' WHEN 'female' THEN 'F'
WHEN 'Louisiana' THEN 'LA' ELSE wpu.meta_value END AS '1',
wpu.user_id, wpgc.timestamp
FROM wp_grassblade_completions AS wpgc
JOIN wp_usermeta AS wpu ON wpgc.user_id = wpu.user_id
WHERE wpgc.timestamp >= ?
AND wpu.meta_key IN ('mepr_full_name', 'mepr_address', 'mepr_city', 'mepr_state',
'mepr_zip_code', 'mepr_home_phone_with_area_code',
'mepr_drivers_license_or_id', 'mepr_id_state',
'mepr_LAst_four_of_social_security_number',
'mepr_date_of_birth_mmddyyyy', 'mepr_sex_mf', 'mepr_height',
'mepr_weight')
AND content_id IN ('1575, 642, 1580')
ORDER BY wpgc.timestamp, wpgc.content_id, wpu.user_id, wpu.meta_key
I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
I'm trying to make my own ORM framework. I get the values from object into arrayList and I'm trying to save them in one time. I have to make for loop to save them all, but I'm confused how to make it?
prepareteState = connect.prepareStatement(Query);
for (int y = 1; y <= obs.size() ; y++) {
for(Object obj : obs){
prepareteState.setObject(y, obj);
System.out.println(Query);
System.out.println(prepareteState.toString());
}
}
prepareteState.execute();
thanks for good advices but, i found the solution :) it is a little bit different than the first idea but, works fine for me:) instead of using prepareState and setObject one by one i`m using StringBuilder to make String and execute query
private String makeInsertQuery(List<String> listOfColumnsNames, List<Object> listOfParameters, String tableName){
StringBuilder columns = new StringBuilder();
StringBuilder parameters = new StringBuilder();
String query = null;
if(listOfColumnsNames != null && listOfColumnsNames.size() != 0 && listOfParameters != null && listOfParameters.size() != 0 && tableName != null){
for(String string : listOfColumnsNames){
columns.append(string + ",");
}
columns.deleteCharAt(columns.length() - 1);
for(Object object : listOfParameters){
parameters.append ("'" + object + "'" + ",");
}
parameters.deleteCharAt(parameters.length() - 1);
query = "INSERT " + "INTO " + tableName + " ( " + columns.toString() + " ) " + " VALUES " + "( " + parameters.toString() + " )" ;
}
//TODO if you need check for null
return query;
}