How can i Skip for loop iterarion in While Loop - for-loop

BigDecimal baseAmt = Env.ZERO;
String sql = "SELECT il.LineNetAmt, COALESCE(il.TaxAmt,0), i.IsSOTrx "
+ "FROM C_InvoiceLine il"
+ " INNER JOIN C_Invoice i ON (il.C_Invoice_ID=i.C_Invoice_ID) "
+ "WHERE il.C_Invoice_ID=? AND il.C_Tax_ID=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getC_Invoice_ID());
pstmt.setInt (2, getC_Tax_ID());
rs = pstmt.executeQuery ();
/*MInvoiceLine[] lines1 = getLines(false);
for (int a = 0; a < lines1.length; a++)
{MInvoiceLine sLine = lines1[a];*/
while (rs.next ())
{
MInvoiceLine[] lines1 = getLines(false);
for (int a = 0; a < lines1.length; a++)
{
MInvoiceLine sLine = lines1[a];
// BaseAmt
baseAmt = rs.getBigDecimal(1);
for (int j = 0; j < cTaxes.length; j++)
{
/*if (!iTax.calculateTaxFromLines1())
return false;*/
MTax cTax = cTaxes[j];
BigDecimal taxAmt = cTax.calculateTax1(baseAmt, isTaxIncluded(), getPrecision());
MInvoiceTaxLine newITax = new MInvoiceTaxLine(getCtx(), 0, get_TrxName());
MProduct product = MProduct.get (getCtx(), sLine.getM_Product_ID());
newITax.setClientOrg(this);
newITax.setC_Invoice_ID(getC_Invoice_ID());
newITax.setC_Tax_ID(cTax.getC_Tax_ID());
//newITax.setPrecision(getPrecision());
//newITax.setIsTaxIncluded(isTaxIncluded());
newITax.setBaseAmount(sLine.getPriceEntered());
newITax.setM_Product_ID(product.getName());
newITax.setBaseAmount(baseAmt);
newITax.setCaculatedTaxAmt(taxAmt);
newITax.saveEx(get_TrxName());
//
if (!isTaxIncluded())
grandTotal = grandTotal.add(taxAmt);
}
}
}
}
catch (SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
}
In above code excution is 1) query the goes in to while loop , and second for loop but i want first it should line1 and second time it should go to while then inside it shloud take second value of line.
Please help me out

Related

Problem two query db2 sqlserver is not print output

This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}

I want to Group questions and answers LINQ and have them display properly

I'm trying to group properly to have my cell distribute eveningly. The printout is coming very odd and uneven.
is it the table i'm creating or group or both? I think the group is correct. My results are as shown in the image below.
Gold is the heading,
Green are the questions,
Red are the answers
Mt table is is below
var Sections = new OncologySection().SelectSections(projectID.ToString());
int iSection = 0;
int igroups = 0;
int ianswer = 0;
tb.CssClass = "";
tb.BorderWidth = 1;
tb.Width = new Unit("780px");
tb.Attributes.Add("runat", "server");
foreach (OncologySection section in Sections)
{
TableRow row1 = new TableRow();
iSection++;
// var getDistinctQuestion = getVoterAnswerstoList.Select(s => s.QuestionText ,s.Id).Distinct().ToList();
var getVoterAnswerstoList = new OncologyGeneratePDFDAL().DataforPDFCreation(Convert.ToInt32(projectID), Convert.ToInt32(voterid), Convert.ToInt32(caseId), Convert.ToInt32(voteSurveyId), Convert.ToInt32(section.SectionID)).OrderBy(os => os.SortOrder);
//var groupedCustomerList = getVoterAnswerstoList
// .GroupBy(u => u.QuestionText, u.QuestionText)
// .Select(grp => grp.ToList())
// .ToList();
var groupedCustomerList = getVoterAnswerstoList.GroupBy(x => new { x.QuestionText, x.DynamicValue }).ToList();
TableCell cell1 = new TableCell();
cell1.BorderWidth = 1;
cell1.Text = section.SectionName;
cell1.BorderColor = System.Drawing.Color.Goldenrod;
cell1.ColumnSpan = groupedCustomerList.Count();
row1.Cells.Add(cell1);
tb.Rows.Add(row1);
TableRow row2 = new TableRow();
foreach (var groups in groupedCustomerList)
{
igroups++;
TableCell cell2 = new TableCell();
var q = (from s in groups select s.QuestionText).FirstOrDefault();
cell2.BorderWidth = 1;
cell2.Text = q;
cell2.BorderColor = System.Drawing.Color.Green;
cell2.ColumnSpan = groupedCustomerList.Count();
row2.Cells.Add(cell2);
if (igroups == groupedCustomerList.Count())
{
tb.Rows.Add(row2);
}
else
{
row2.Cells.Add(cell2);
}
TableRow row3 = new TableRow();
foreach (var answers in groups)
{
ianswer++;
TableCell cell3 = new TableCell();
cell3.BorderWidth = 1;
cell3.BorderColor = System.Drawing.Color.DarkRed;
if (answers.DataTypeId == 7)
{
cell3.Text = answers.DynamicValue.ToString();
}
else if ((answers.DataTypeId == 5) || (answers.DataTypeId == 6) || (answers.DataTypeId == 8))
{
if (answers.VotingValue != 0)
{
cell3.Text = answers.VotingValue.ToString();
}
else
{
cell3.Text = " ";
}
}
else
{
cell3.Text = " ";
}
row3.Cells.Add(cell3);
tb.Rows.Add(row3);
}
}
}
}

How to insert a huge amout of data to oracle database?

First I query some data from user A and then I need to insert all this data to user B (user in oracle I mean) and I use Java to solve it. Below is my code:
while (ds.getResultSet().next()) {
ResultSet resultSet = ds.getResultSet();
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount();
StringBuilder sb = new StringBuilder();
sb.append("insert into ");
sb.append(tableName.toUpperCase());
sb.append("(");
for (int i = 1; i <= count; i++) {
sb.append(metaData.getColumnName(i));
if (i != count) sb.append(",");
else sb.append(")");
}
sb.append(" values(");
for (int i = 1; i <= count; i++) {
Object colValue = resultSet.getObject(i);
if (colValue == null) {
sb.append("null");
} else {
if (colValue instanceof Date) {
Date d = resultSet.getDate(i);
String dateStr = DateUtils.formatDate(d, "yyyy-MM-dd hh:mm:ss");
sb.append("to_date(");
sb.append("'");
sb.append(dateStr);
sb.append("','yyyy-MM-dd hh24:mi:ss')");
} else {
sb.append("'");
sb.append(resultSet.getObject(i));
sb.append("'");
}
}
if (i != count) sb.append(",");
else sb.append(")");
}
conn = datasource.getConnection();
System.out.println(sb.toString());
ps = conn.prepareStatement(sb.toString());
ps.execute();
}
So it works a bit, but when it inserts above 80 records oracle just collaspses, and it's warning me in the console:
Can you guys give some advice to me about this? Thanks for your time.
Do not use Java - just do it all in Oracle.
INSERT INTO b.table_name ( col1, col2, col3, col4 )
SELECT col1, col2, col3, col4
FROM a.table_name
WHERE some_column = some_value; -- Add filters if necessary
You avoid having to dynamically build the query by parsing the meta-data.
You avoid errors where you are not escaping single quotes.
Further to this, you avoid potential SQL Injection attacks where a user could enter something like the string value', (SELECT password_hash FROM users WHERE userid = 'Admin1' ) ) --
As you guys suggest, I changed my code like below:
Connection conn = DriverManager.getConnection(url, user, pwd);
PreparedStatement pspt = conn.prepareStatement("select * from SYS_DICT_TYPE");
ResultSet resultSet = pspt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
StringBuilder sql = new StringBuilder();
sql.append("insert into TEST_SYS (");
for (int i = 1; i <= columnCount; i++) {
sql.append(metaData.getColumnName(i));
if (i != columnCount) sql.append(",");
}
sql.append(") values(");
for (int i = 1; i <= columnCount; i++) {
sql.append("?");
if (i != columnCount) sql.append(",");
}
sql.append(")");
String s = sql.toString();
PreparedStatement pspt2 = conn.prepareStatement(s);
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
pspt2.setObject(i, resultSet.getObject(i));
}
pspt2.addBatch();
}
pspt2.executeBatch();
The wired thing is: At the first I build the statement end with a ';'
(the sql clause should like insert into tablename values(?,?);)
which cause ora-00933:SQL error.When I removed the ';' it worked perfectly well.Why could this happend?

Spring Boot example how to download file from server

I have a Spring Boot web application and I need an example of how to download a file from the server.
Thanks,
R.
I have this running project of SpringBoot. Below is a part of code which outputs xlsx file.
WebController.java
#RequestMapping(value = {"/excel"}, method = RequestMethod.GET)
public void excel(HttpServletResponse response, #RequestParam("email") String email) {
try {
Query query = new Query();
query.addCriteria(Criteria.where("email").is(email));
if(email.equals(""))
query=new Query();
List<MQTT_Server_Detail> list = mongoTemplate.find(query, MQTT_Server_Detail.class, "owner");
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
Workbook workbook = new XSSFWorkbook();
workbook.createSheet("owner");
workbook.setSheetName(0, "Owner");
Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0);
sheet.getRow(0).createCell(0).setCellValue("Owner Email");
sheet.getRow(0).createCell(1).setCellValue("Topic");
sheet.getRow(0).createCell(2).setCellValue("Device Name");
sheet.getRow(0).createCell(3).setCellValue("Device ID");
Row row;
int num = 1;
for (MQTT_Server_Detail a : list) {
Devices devices = getDevice(a.getEmail());
for (int i = 0; i < devices.getDevicesID().size(); i++) {
row = sheet.createRow(num++);
row.createCell(0).setCellValue(a.getEmail());
row.createCell(1).setCellValue(a.getTopic());
row.createCell(2).setCellValue((String) devices.getDevicesName().get(i));
row.createCell(3).setCellValue((String) devices.getDevicesID().get(i));
}
}
sheet = workbook.createSheet("Users");
row = sheet.createRow(0);
row.createCell(0).setCellValue("Name");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("CardID");
row.createCell(3).setCellValue("Email");
row.createCell(4).setCellValue("Mobile");
row.createCell(5).setCellValue("Blocked");
row.createCell(6).setCellValue("Last in Date");
row.createCell(7).setCellValue("Last in Time");
row.createCell(8).setCellValue("Last out Date");
row.createCell(9).setCellValue("Last out Time");
row.createCell(10).setCellValue("Owner");
Criteria criteria[] = new Criteria[list.size()];
for (int i = 0; i < list.size(); i++) {
criteria[i] = Criteria.where("owner").is(list.get(i).getEmail());
}
List<Users_POJO> users_pojoList;
if (list.size() == 0)
users_pojoList = new ArrayList<>();
else
users_pojoList = mongoTemplate.find(new Query().addCriteria(new Criteria().orOperator(criteria)),
Users_POJO.class, "users");
for (int i = 0; i < users_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(users_pojoList.get(i).getName());
row.createCell(1).setCellValue(users_pojoList.get(i).getDevice());
row.createCell(2).setCellValue(users_pojoList.get(i).getCard_id());
row.createCell(3).setCellValue(users_pojoList.get(i).getEmail());
row.createCell(4).setCellValue(users_pojoList.get(i).getMobile());
row.createCell(5).setCellValue(users_pojoList.get(i).getBlocked());
row.createCell(6).setCellValue(users_pojoList.get(i).getLast_in_date());
row.createCell(7).setCellValue(users_pojoList.get(i).getLast_in_time());
row.createCell(8).setCellValue(users_pojoList.get(i).getLast_out_date());
row.createCell(9).setCellValue(users_pojoList.get(i).getLast_out_time());
row.createCell(10).setCellValue(users_pojoList.get(i).getOwner());
}
sheet = workbook.createSheet("Logs");
row = sheet.createRow(0);
row.createCell(0).setCellValue("CardID");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("Date");
row.createCell(3).setCellValue("Time");
row.createCell(4).setCellValue("Count");
criteria = new Criteria[users_pojoList.size()];
for (int i = 0; i < users_pojoList.size(); i++) {
criteria[i] = Criteria.where("card_id").is(users_pojoList.get(i).getCard_id());
}
query = new Query();
query.addCriteria(new Criteria().orOperator(criteria));
List<Log_POJO> log_pojoList;
if (users_pojoList.size() == 0)
log_pojoList = new ArrayList<>();
else
log_pojoList = mongoTemplate.find(query, Log_POJO.class, "logs");
for (int i = 0; i < log_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(log_pojoList.get(i).getCard_id());
row.createCell(1).setCellValue(log_pojoList.get(i).getDevice());
String date = log_pojoList.get(i).getDay() + "-" + log_pojoList.get(i).getMonth() + "-" + log_pojoList.get(i).getYear();
row.createCell(2).setCellValue(date);
String time = log_pojoList.get(i).getHour() + "-" + log_pojoList.get(i).getMin() + "-" + log_pojoList.get(i).getSec();
row.createCell(3).setCellValue(time);
row.createCell(4).setCellValue(log_pojoList.get(i).getSerial_no());
}
workbook.write(response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
In short, you have to do this:
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
//get the outputstream of response and write data to it
Spring Boot download file from server
#Controller
#RequestMapping(value = "/")
public class HomeController {
#RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"webpage.html\"");
InputStream inputStream = new FileInputStream(new File("C:\\MyWebPage\\webpage.html"));
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}
}

split one big datatable to two separated datatables

I´m exporting datatables to Excel workbook. Problem is that the datatable holds 90000 rows and excel can only hold 67000 rows in every sheet.
So..
How can i divide one big datatable to two datatables, maybe with Linq ?
Then i can have datatable1 in sheet1 and datatable2 in sheet2
Sincerly
agh
Assuming that you're getting the 90,000 rows for this DataTable from a database somewhere, the most efficient approach would be to modify your SELECT statement into two new SELECT statements, each of which returns < 67,000 rows, and then do everything else the same.
Split your recordset. Perform one SELECT that extracts all 90,000 rows, and split it on Excel import step.
private List<DataTable> CloneTable(DataTable tableToClone, int countLimit)//Split function
{
List<DataTable> tables = new List<DataTable>();
int count = 0;
DataTable copyTable = null;
foreach (DataRow dr in tableToClone.Rows)
{
if ((count++ % countLimit) == 0)
{
copyTable = new DataTable();
copyTable = tableToClone.Clone();
copyTable.TableName = "Sample" + count;
tables.Add(copyTable);
}
copyTable.ImportRow(dr);
}
return tables;
}
protected void LinkReport_Click(object sender, EventArgs e)
{
DataTable dt2 = (DataTable)ViewState["dtab"];
List<DataTable> dt1 = CloneTable(dt2, 5);
DataSet ds = new DataSet("dst");
for (int i = 0; i < dt1.Count; i++)
{
ds.Tables.Add(dt1[i]);
}
string filePath = Server.MapPath("Reports/").ToString() + "master.xls";
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
file.Delete();
}
Export(ds, filePath);// Export into Excel
}
Clone - The fastest method to create tables with original columns structure is Clone method.
Export into Excel
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
public void Export(DataSet ds, string filePath)
{
string data = null;
string columnName = null;
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
//Excel.Worksheet xlWorkSheet;
Excel.Worksheet xlWorkSheet = null;
object misValue = System.Reflection.Missing.Value;
Excel.Range range;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int l = 0; l < ds.Tables.Count; l++)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(l + 1);
xlWorkSheet.Cells[1, 1] = "Report";
xlWorkSheet.get_Range("A1:D1", Type.Missing).Merge(Type.Missing);
xlWorkSheet.get_Range("A1", "D1").Font.Bold = true;
xlWorkSheet.Cells.Font.Name = "Courier New";
if (l == 0)
{
xlWorkSheet.Name = "Sheet1";
}
else if (l == 1)
{
xlWorkSheet.Name = "Sheet2";
}
else if (l == 2)
{
xlWorkSheet.Name = "Sheet3";
}
else if (l == 3)
{
xlWorkSheet.Name = "Sheet4";
}
else if (l == 4)
{
xlWorkSheet.Name = "Sheet5";
}
for (i = 0; i <= ds.Tables[l].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[l].Columns.Count - 1; j++)
{
columnName = ds.Tables[l].Columns[j].ColumnName.ToString();
xlWorkSheet.Cells[3, j + 1] = columnName;
data = ds.Tables[l].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 5, j + 1] = data;
}
}
}
//for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
//{
// for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
// {
// data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
// xlWorkSheet1.Cells[i + 1, j + 1] = data;
// }
//}
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
// kill all excel processes
Process[] pros = Process.GetProcesses();
for (int p = 0; p < pros.Length; p++)
{
if (pros[p].ProcessName.ToLower().Contains("excel"))
{
pros[p].Kill();
break;
}
}
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Try this One.. I have Worked out in Visual Studio 2005
DataTable[] splittedtables = dt.AsEnumerable()
.Select((row, index) => new { row, index })
.GroupBy(x => x.index / Input From User) // integer division, the fractional part is truncated
.Select(g => g.Select(x => x.row).CopyToDataTable())
.ToArray();
This should work.

Resources