How to execute queries in a for loop
Ok, here is the problem. I have a database which contains web page content. When you start the program, the user types in a string and that string is split up into its separate words and stored in a list. Then you are asked for the logic, such as exact, all, or any. I didn't put any in the code yet, so don't worry about that one. exact is simple, I query the pageContent for that word and I print out all rows that were found with the string that was entered. all is easy with just one word, but lets say I have the string "how are you". The tokenizer would store three words in the list which is a String[]. Now for all, in order for the user to get back any results, all of the words, not in the order have to be found in the pageContent, but I can't figure out how to do this. Basically, I'm looking for a way to query the database using AND this case in some kind of loop. The code below should clear somethings up:
import java.io.*;
import java.sql.*;
import java.util.*;
public class simpleTest {
public static void main(String[] args) throws IOException {
int rows = 0;
int count = 0;
String[] wordList = new String[50];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {System.out.println("No driver");}
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/cop4610webs",
"root", "anatoly");
// Do something with the Connection
System.out.println("Enter a string: ");
String word = reader.readLine();
StringTokenizer words = new StringTokenizer(word);
while(words.hasMoreTokens())
wordList[count++] = words.nextToken();
System.out.println("Enter the logic");
String logic = reader.readLine();
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
if(logic.equalsIgnoreCase("exact"))
rs = stmt.executeQuery("SELECT pageName FROM pages WHERE pageContent ='"+word+"'");
ResultSetMetaData metaData = rs.getMetaData();
System.out.println("Results of SELECT");
rs.last(); //move to last row
rows = rs.getRow(); //check rows returned
System.out.println(rows);
rs.beforeFirst(); //move back to beginning
if(rows != 0)
rs.next();
System.out.println(rs.getObject(1) );
while ( rs.next() ) {
System.out.println(rs.getObject(1) );
else
if(logic.equalsIgnoreCase("all"))
rs = stmt.executeQuery("SELECT pageName FROM pages WHERE pageContent ='"+word+"'");
System.out.println("Results of SELECT");
rs.last(); //move to last row
rows = rs.getRow(); //check rows returned
System.out.println(rows);
rs.beforeFirst(); //move back to beginning
if(rows != 0)
rs.next();
System.out.println(rs.getObject(1) );
while ( rs.next() ) {
System.out.println(rs.getObject(1) );
rs.close();
} catch (SQLException ex) { // handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
Works towards getting a sql statement something like this:
SELECT pageName FROM pages WHERE pageContent LIKE '%word1%' AND pageContent LIKE '%word2%' AND pageContent LIKE '%word3%';
Similar Messages
-
How to let " i " of a for loop to start from a "X"
Hi,
how to let " i " of a for loop to start from a value "x" where x is a variable?
Thx
Message Edited by starfish on 10-19-2007 06:00 AMHi starfish,
use it like this:
If this doesn't fit your needs you should attach an example of what you really need!
Message Edited by GerdW on 10-19-2007 01:15 PM
Best regards,
GerdW
CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
Kudos are welcome
Attachments:
I.png 2 KB -
Please help me.. how to rewrite the following java- for loop code in ada
int i, j, n = 100;
for (i = 0, j = 17; i < n; i++, j-- )
sum += i * j + 3;how to rewrite the following java- for loop code in ada
You should have a programming manual for Ada first. If you mean it the other way round, I think you subject line confused me. -
How to optimize the select query that is executed in a cursor for loop?
Hi Friends,
I have executed the code below and clocked the times for every line of the code using DBMS_PROFILER.
CREATE OR REPLACE PROCEDURE TEST
AS
p_file_id NUMBER := 151;
v_shipper_ind ah_item.shipper_ind%TYPE;
v_sales_reserve_ind ah_item.special_sales_reserve_ind%TYPE;
v_location_indicator ah_item.exe_location_ind%TYPE;
CURSOR activity_c
IS
SELECT *
FROM ah_activity_internal
WHERE status_id = 30
AND file_id = p_file_id;
BEGIN
DBMS_PROFILER.start_profiler ('TEST');
FOR rec IN activity_c
LOOP
SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
FROM ah_item --464000 rows in this table
WHERE item_id_edw IN (
SELECT item_id_edw
FROM ah_item_xref --700000 rows in this table
WHERE item_code_cust = rec.item_code_cust
AND facility_num IN (
SELECT facility_code
FROM ah_chain_div_facility --17 rows in this table
WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
AND div_id = (SELECT div_id
FROM ah_div --8 rows in this table
WHERE division = rec.division)));
END LOOP;
DBMS_PROFILER.stop_profiler;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
NULL;
WHEN TOO_MANY_ROWS
THEN
NULL;
END TEST;The SELECT query inside the cursor FOR LOOP took 773 seconds.
I have tried using BULK COLLECT instead of cursor for loop but it did not help.
When I took out the select query separately and executed with a sample value then it gave the results in a flash of second.
All the tables have primary key indexes.
Any ideas what can be done to make this code perform better?
Thanks,
Raj.As suggested I'd try merging the queries into a single SQL. You could also rewrite your IN clauses as JOINs and see if that helps, e.g.
SELECT DISTINCT ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
WHERE ai.item_id_edw = aix.item_id_edw
AND aix.item_code_cust = rec.item_code_cust
AND aix.facility_num = acdf.facility_code
AND acdf.chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
AND acdf.div_id = ad.div_id
AND ad.division = rec.division;ALSO: You are calling ah_internal_data_pkg.get_chain_id (p_file_id) every time. Why not do it outside the loop and just use a variable in the inner query? That will prevent context switching and improve speed.
Edited by: Dave Hemming on Dec 3, 2008 9:34 AM -
How to pass parameter to cursor for loop having table type?
Hi Friends,
I am wondering how to pass a parameter into second for loop in the example code below.Please see the bold statements and answer my queries.
Thanks a lot .Here is the code .
declare
l_bom_header_tbl BOM_BO_PUB.BOM_HEADER_TBL_TYPE ; ---TABLE TYPE
V_bom_header_tbl Bom_Bo_Pub.Bom_Head_Rec_Type := Bom_Bo_Pub.G_MISS_BOM_HEADER_REC; ---Record type
v_bom_components_tbl Bom_Bo_Pub.Bom_Comps_Tbl_Type := Bom_Bo_Pub.G_MISS_BOM_COMPONENT_TBL;---nested table type
c:=0 number ;
k:=1 number ;
begin
BOMPXINQ.Export_BOM(
P_org_hierarchy_name => l_org_hierarchy_name,
P_assembly_item_name => l_assembly_item_name,
P_organization_code => l_organization_code,
P_alternate_bm_designator => '1Test',
P_Costs => l_costs,
P_Cost_type_id => l_cost_type_id,
X_bom_header_tbl => l_bom_header_tbl,
X_bom_revisions_tbl => l_bom_revisions_tbl,
X_bom_components_tbl => l_bom_components_tbl,
X_bom_ref_designators_tbl => l_bom_ref_designators_tbl,
X_bom_sub_components_tbl => l_bom_sub_components_tbl,
X_bom_comp_ops_tbl => l_bom_comp_ops_tbl,
X_Err_Msg => l_Err_Msg,
X_Error_Code => l_Error_Code);
if l_Error_Code = 0 then
for i in 1 .. l_bom_header_tbl.COUNT LOOP
V_bom_header_tbl.organization_code :='DSC';
Can we assign a table type to record type like below statement?
V_bom_header_tbl.assembly_item_name:= l_bom_header_tbl(i).assembly_item_name ;
k:=1;
I want to pass parameter l_bom_header_tbl(i).assembly_item_name into the for statement below: How to achieve this?
for j in 1 .. l_bom_components_tbl.COUNT LOOP
Can we assign a table type to table type like below statement?
v_bom_components_tbl(k).Assembly_Item_name := l_bom_header_tbl(i).assembly_item_name ;
k := k + 1;
end LOOP;
end loop;
end;
Edited by: ILovePlSql on Mar 22, 2010 7:51 AM
Edited by: ILovePlSql on Mar 22, 2010 8:16 AMILovePlSql wrote:
V_bom_header_tbl.assembly_item_name:= l_bom_header_tbl(i).assembly_item_name ;
v_bom_header_tabl is a record type and l_bom_header_tbl is a table type .So is the above statement ok?I asked you for type definition. Please provide definition of BOM_BO_PUB.BOM_HEADER_TBL_TYPE and Bom_Bo_Pub.Bom_Head_Rec_Type. If BOM_BO_PUB.BOM_HEADER_TBL_TYPE is table of Bom_Bo_Pub.Bom_Head_Rec_Type then your statment is OK. For example:
SQL> declare
2 type BOM_HEADER_TBL_TYPE is table of emp%rowtype index by binary_integer;
3 l_bom_header_tbl BOM_HEADER_TBL_TYPE;
4 V_bom_header_tbl emp%rowtype;
5 begin
6 select * bulk collect into l_bom_header_tbl from emp;
7 for i in 1 .. l_bom_header_tbl.count loop
8 V_bom_header_tbl.ename := l_bom_header_tbl(i).ename;
9 end loop;
10 end;
11 /
PL/SQL procedure successfully completed.
SQL> SY. -
How do I use an enhanced for loop / for each on my ViewObjectImpl ?
Guys and Gals,
With all of my newly acquired Java knowledge in tow, I spent this weekend cleaning up all of my code, dealing mainly with for loops. I converted them from a huge mess to a for each type loop using language such as ...
RowSet priceUpdateRows = (RowSet)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
for (Row priceUpdateRow: priceUpdateRows)
{ // do operations on row... which makes perfect sense to me. For each Row in the RowSet, do something. It doesn't, however, makes sense to the compiler. It pouts and gives me a "foreach not applicable to expression type" error. So I read up on iterators and such, messed with code examples, and still can't get the RowSet to iterate with the above code. Could I make RowSet implement Iterable? How would I do that? I tried to create a class called RowSetExt which extended RowSet and implemented Iterable, but then I got a class cast exception.
I know I could implement something like the following or a while(hasNext()) but they're really not what I'm looking for.
ViewObject vo = … < Get ViewObject > …
RowSetIterator rsi = vo.createRowSetIterator("rowsRSI");
while (rsi.hasNext())
Row row = rsi.next();
row.setAttribute("YourAttribute",your_value);
rsi.closeRowSetIterator();How do I make the for(Row row : <RowSet>) example work? Or could someone point me in a direction?
WillOne thing I tried was to make a framework extension class for my ViewObjectImpls
public class PcsViewObjectImpl
extends ViewObjectImpl
implements Iterable<Row>
Set<Row> set = new HashSet<Row>();
public Iterator<Row> getRows()
return set.iterator();
public Iterator<Row> iterator()
return getRows();
}AppModuleImpl
PriceUpdateRowsViewRowImpl priceUpdateRows = (PriceUpdateRowsViewRowImpl)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
for (Row priceUpdateRow: priceUpdateRows)
{However, this gives me a class cast exception at runtime. But I would think some kind of extension class would be the way to go ... ? -
How to pass parameter into cursor for loop ?
Hi Experts,
I want to pass parameter l_bom_header_tbl(i).assembly_item_name into the for statement below How to achieve this?
for j in 1 .. l_bom_components_tbl.COUNT LOOP
ThanksMaybe i failed to describe in detail,so here i go:
I have two for loops:
for i in 1 .. l_bom_header_tbl.COUNT LOOP --1st For Loop
V_bom_header_tbl.organization_code :='DSC';
V_bom_header_tbl.assembly_item_name:= l_bom_header_tbl(i).assembly_item_name ;
k:=1;
I want to pass parameter l_bom_header_tbl(i).assembly_item_name into the for statement below: How to achieve this?
for j in 1 .. l_bom_components_tbl.COUNT LOOP *2nd For Loop*
v_bom_components_tbl(k).Assembly_Item_name := l_bom_header_tbl(i).assembly_item_name ;
k := k + 1;
end LOOP;
end loop;
end;
I want to pass a paramter into second for loop in such a way that it accepts from the first for loop
for j in 1 .. l_bom_components_tbl.COUNT LOOP -2nd loop
Edited by: ILovePlSql on Mar 22, 2010 12:25 PM -
How to maintain counter in a for loop
Hi,
How do we track counter in a loop?Isn't it the way I implemented.? Please suggest.
Regards.
Solved!
Go to Solution.
Attachments:
for loop counter.jpg 219 KBBoth loops have errors, if you try to do for(i=60;i<120;i++) you're only running 60 loops, not 120.
You should also disable the autoindexing on incoming arrays as you want some split array indexes (actually you can optimize it by extracting the constant a[30] before the 1st loop and the opposite on the 2nd. Now you're extracting 2 numbers from a 1D array instead of 1 from a 2D array ...
The number on the select/sum function should be integers, no need to calculate doubles.
The small array to sum it up is only max 170 numbers, it's ok although a sum in a shift register would be better.
/Y
LabVIEW 8.2 - 2014
"Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
G# - Free award winning reference based OOP for LV -
How to check two contitions in for loop
Hello all
Here I am having a for loop where I am reading from a cursor and I want to run this loop
till the number in :P102_NO
FOR emp_rec in emp_cur and i in 1 to :P102_NO loop
insert into EMP(EMP_ID,DEATH_DATE) values(emp_rec.emp_id,:P102_DATE)
end loop;
but it is showing a error:
ORA-06550: line 5, column 24: PLS-00103: Encountered the symbol "AND" when expecting one of the following: . ( * @ % & - + / at loop mod remainder rem .. || multiset
do anybody have any idea about it?
Thanks
TauceefTauceef wrote:
Hello all
Here I am having a for loop where I am reading from a cursor and I want to run this loop
till the number in :P102_NO
FOR emp_rec in emp_cur and i in 1 to :P102_NO loop
insert into EMP(EMP_ID,DEATH_DATE) values(emp_rec.emp_id,:P102_DATE)
end loop;
but it is showing a error:
ORA-06550: line 5, column 24: PLS-00103: Encountered the symbol "AND" when expecting one of the following: . ( * @ % & - + / at loop mod remainder rem .. || multiset
do anybody have any idea about it?
Thanks
TauceefYou would need 2 loops, but the ideal way to do this would be in a single SQL statement... no loops, no cursors.
FOR emp_rec in emp_cur
LOOP
FOR i in 1 to :P102_NO
LOOP
<stuff and or things>
END LOOP;
END LOOP;However you aren't making reference to your variable (i) anywhere ... so what exactly are you trying to do?
How about you show us your cursor, the data you have ... and the data you want when whatever the heck you're trying to do 'works'. We'll be in a much better-er position to help you in that case. -
How to terminate or exit a for loop when the user clicks on stop button
Actually my problem is to stop a loop when i click on stop button.
example:i have two buttons 'start' and 'stop'
in start buttom i wrote a for loop as
dim i as integer
For i=1 To 100000
print i
Next
when i click on start buuton it prints 'i' value up tp 100000.
my question is when i click on 'Stop' button the for loop has to terminate or Exit from the loop and should stops the execution.
Is it possible to termianate or Exit the 'for loop'
PS.Shakeer Hussain
HyderabadI am unable to stop the loop and application not at all allowing to Press the Stop button.
It seems like Hung, any advise ?
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
btnStop.Enabled = True
btnSelectFile.Enabled = False
btnStart.Enabled = False
btnStop.Focus()
Dim strFileName As String = txtFileName.Text.ToString
Dim strLineText As String
If System.IO.File.Exists(strFileName) = True Then
Dim objReader As New System.IO.StreamReader(strFileName)
While objReader.Peek() <> -1 And stopclick = False
strLineText = objReader.ReadLine()
MsgBox(strLineText, MsgBoxStyle.Information)
Application.DoEvents()
Thread.Sleep(My.Settings("strDelay") * 1000)
'System.Diagnostics.Process.Start(My.Settings("strFireFoxLocation"), strLineText)
End While
End If
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
stopclick = True
btnSelectFile.Enabled = True
btnStart.Enabled = True
btnStop.Enabled = False
End Sub
Raman Katwal
Please remember to mark the replies as answers if they help and unmark them if they provide no help -
How to stop and start a for loop
I've got code and a for loop running in a while loop. What I need to do is simply pause the operation of the for loop until an requirement is met, and but maintain its iteration position throughout each pause interval (not necessarily timed, just paused until the next requirement is met). I've tried wiring a boolean to the "continue if true" terminal of the for loop, but the iteration count restarts to 0 when the loop is started again. Is there a way to stop the for loop, and continue at the particular iteration it is at?
Solved!
Go to Solution.Breakpoints, whether normal or conditional, are just meant for debugging of your code. I had the sense from your question that the pausing you want to do is a part of normal operation of your code. I would NOT recommend using a breakpoint for that situation. It would bring up the block diagram showing the breakpoint when it occurs. A user besides the programmer would not know what to do in that case.
Yes, both the inner and outer loops would have shift registers.
Putting a case structure with a small while loop inside the "Pausing Case" is doable. It just depends on what you are doing or waiting for while the program operation is "paused". -
How to use reverse function in FOR loop
Hi,
Can we use REVERSE function in for loop.
If so can u please give an explanation with some example.
Thanks in advance.
Satya.In SQL you could do this...
SQL> ed
Wrote file afiedt.buf
1 select empno, ename, replace(sys_connect_by_path(ch,'|'),'|') as rev_ename
2 from (
3 select empno, ename, case when rn <= length(ename) then substr(ename, length(ename)-rn+1, 1) else null end as ch, rn
4 from emp
5 ,(select rownum as rn from dual connect by rownum <= (select max(length(ename)) from emp))
6 where case when rn <= length(ename) then substr(ename, length(ename)-rn+1, 1) else null end is not null
7 )
8 where connect_by_isleaf = 1
9 connect by empno = prior empno and rn = prior rn + 1
10 start with rn = 1
11* order by empno
SQL> /
EMPNO ENAME REV_ENAME
7369 SMITH HTIMS
7499 ALLEN NELLA
7521 WARD DRAW
7566 JONES SENOJ
7654 MARTIN NITRAM
7698 BLAKE EKALB
7782 CLARK KRALC
7788 SCOTT TTOCS
7839 KING GNIK
7844 TURNER RENRUT
7876 ADAMS SMADA
7900 JAMES SEMAJ
7902 FORD DROF
7934 MILLER RELLIM
14 rows selected.
SQL> -
How to pause and stop two "for loops" in an event
Hi
The main menu runs first and then goes to reading menu. After "Start Reading" button is pressed, the reading process will take readings.
1) During reading process, if the "Pause Reading" button is pressed, I want that the two "for loops" are stopped and the two "for loop" counters do not reset. After the "Start Reading" button is pressed, the two "for loops" will continue to run.
2) During reading process, if the "Stop Reading" button is pressed, I want that the two "for loops" are stopped and the two "for loop" counters are reset. After the "Start Reading" button is pressed, the two "for loops" will run again.
The attached two VIs are simplified my real application. Any help will be appreciated.
Thanks
Steve
Attachments:
Main Menu Test.vi 9 KB
Reading Menu Test.vi 23 KBYou can't have those loops inside of the event structure. Currently, when you press the start button, the reading has to finish before the event case finishes. This will prevent the stop can cancel buttons from being processed by the event structure.
You need another loop that can recieve commands from the event loop. Look up the Queued Message Handler. That should get you a good start on the command process.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
How to output data outtside a for loop every 10 iterations​?
Hi friends,
does any body help me to sort out this problem?
please check the attchement for my vi.
all i want is output data from inside for loop to outside for loop every 10 iterations. please do not use local variable.
Many thanks
dan
Attachments:
output.vi 16 KBHi Dan,
I am not sure what you want to do every 10 iterations with the value outside, but If you want to update your graph every 10 iterations use the following way:
If you want to handle the specific value every x iterations outside the loop you could either use queues or notifieres.
BR,
ThSa
Message Edited by ThSa on 08-23-2006 09:05 PM
http://www.newgistics.com
Attachments:
1.png 6 KB -
How does array obtained in a for loop?
Hi
I went previosly my question as below.
"Firstly thanks for help,
I want to obtain array from the y value calculated in the for loop .at every loop, and in same for loop these different arrays are operated.so with one for loop the calculates are obtained.
Thanks"
Now could you give me one sample program?
Thanks a lot.LabVIEW ships with a variety of examples. Search through those (hint: look under fundamentals>>arrays) to find what you are looking for.
Maybe you are looking for
-
External SSD drive not working with mavericks anymore!
The second I upgraded to Mavericks and used my external SSD drive, my external drive stopped working. I also doesnt want to initialize anymore either in disk utility! Can someone from apple please tell me whats going on?
-
When I try to install Adobe AIR version 14.0 on my Mac OS X Version 10.9.4 I receive the following message. An earlier versions of Adobe AIR worked on earlier versions Mac OS on my computer. Does anyone have Adobe AIR working on the latest version of
-
P.O Pricing Condition Record
Hi Which Tcode to maintain the Purchase order condition record (Specifically for the Tax Condition). Rgds RG.
-
"Log on failed" with ODBC and Stored Procedure
I am in the process of porting our application from CR10 to CR.NET and am having some trouble setting the log on info. I have a report that was designed against a stored procedure and a development database. The connection at design time is ODBC to
-
How to make Double Click To Edit work instead of ClickToEdit for Af:Table
Hi All, We use AF:Table in clickToEdit mode and most of the time the users use this table for selecting a master record then work on the detail records. To avoid the cost of rendering the selected row as editable we would like to change the behavior