String Array to Comma spearated list
Hey Guys,
I have a struts application that receives a string[] array of product numbers corresponding to those that a user has selected. I need to put these into a SQL query in the form of "PRODUCTS.PRODUCT_NAME IN ('product1','product2','product3')" -- in otherwords, a comma separated list, with each item wrapped in apostrophes.
I can successfully drop in individual items using notation like the following:
<c:set var="where" value="and PRODUCTS.PRODUCT_NAME IN ('${formChecker4.selectedProductListForm2[0]}')" />What I'm not sure about is the best way to create my comma separated list. In my formChecker4 class, I have getSelectedProductListForm2() and setSelectedProductListForm2() methods, but these expect and return a string[] array, not a plain string. Does anyone have any handy suggestions for converting my array into a string, either within my class or within my EL tags?
Here's some of my formChecker4 class:
private String[] selectedProductListForm2;
public String[] getSelectedProductListForm2() {
return this.selectedProductListForm2;
public void setSelectedProductListForm2(String[] selectedProductListForm2) {
if (selectedProductListForm2.length == 0) {
this.selectedProductListForm2 = null;
} else {
this.selectedProductListForm2 = selectedProductListForm2;
}
1) don't do it in JSP
2) [Use a prepared statement. |http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html]
Similar Messages
-
Make a string into a comma delimited list
I imagine someone out there has done this before, I am
struggling with the right code to get it done. Please see code, any
suggestions welcome and much appreciate in advance - thanksTry the code below. At the end of the loop, remove the extra
comma at the end of the string. -
Obtaining comma-separated list of text values associated with bitwise flag column
In the table msdb.dbo.sysjobsteps, there is a [flags] column, which is a bit array with the following possible values:
0: Overwrite output file
2: Append to output file
4: Write Transact-SQL job step output to step history
8: Write log to table (overwrite existing history)
16: Write log to table (append to existing history)
32: Include step output in history
64: Create a Windows event to use as a signal for the Cmd jobstep to abort
I want to display a comma-separated list of the text values for a row. For example, if [flags] = 12, I want to display 'Write Transact-SQL job step output to step history, Write log to table (overwrite existing history)'.
What is the most efficient way to accomplish this?Here is a query that gives the pattern:
DECLARE @val int = 43
;WITH numbers AS (
SELECT power(2, n) AS exp2 FROM (VALUES(0), (1), (2), (3), (4), (5), (6)) AS n(n)
), list(list) AS (
SELECT
(SELECT CASE WHEN exp2 = 1 THEN 'First flag'
WHEN exp2 = 2 THEN 'Flag 2'
WHEN exp2 = 4 THEN 'Third flag'
WHEN exp2 = 8 THEN 'IV Flag'
WHEN exp2 = 16 THEN 'Flag #5'
WHEN exp2 = 32 THEN 'Another flag'
WHEN exp2 = 64 THEN 'My lucky flag'
END + ', '
FROM numbers
WHERE exp2 & @val = exp2
ORDER BY exp2
FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)')
SELECT substring(list, 1, len(list) - 1)
FROM list
Here I'm creating the numbers on the fly, but it is better to have a table of numbers in your database. It can be used in many places, see here for a short discussion:
http://www.sommarskog.se/arrays-in-sql-2005.html#numbersasconcept
(Only read down to the next header.)
For FOR XML PATH thing is the somewhat obscure way we create concatenated lists. There is not really any using trying to explain how it works; it just works. The one thing to keep in mind is that it adds an extra comma at the end and the final query strips
it off.
This query does not handle that 0 has a special meaning - that is left as an exercise to the reader.
Erland Sommarskog, SQL Server MVP, [email protected] -
Exporting a String Array to an HTML file
Hey everyone..I'm currently making lots of progress in my project...but right now I've been trying to make a button that exports my search results to an html file...basically what I've made is a search engine to search webcrawler files...
The result list I get (which is actually a string array), I want to export to html so I can open that html file and find all the links that were found in the search I made..What I have so far is this, but it's not working yet, any help? :
private class exportListener implements ActionListener
public void actionPerformed(ActionEvent e)
String[] result = parent.getResult();
if(result == null)
return;
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new HtmlFileFilter());
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
int returnVal = chooser.showSaveDialog(parent);
if(returnVal == JFileChooser.CANCEL_OPTION)
return;
File fl = chooser.getSelectedFile();
String path = fl.getPath() + ".html";
searchIF.exportResultAsHtml(path);
System.out.println(path);
private class HtmlFileFilter extends FileFilter
public String getDescription(){return "Html";}
public boolean accept(File pathname)
String name = pathname.getPath();
//Just checking to see if the filename ends with html.
if (name.toLowerCase().substring(name.lastIndexOf('.') + 1).equals("html"))
return true;
return false;
}Actually..nevermind, sorry.
-
Converting vector to string array
How can I convert values in a vector into a string array?
Vector formsVector = new Vector();
while (rs.next())
{formsVector.add(rs.getString("forms"));}
String forms[] = (String[])formsVector.toArray();
I tried the above line but it did not work. Any input please?
Thanks.... What is the difference between the two as
according to online help, both are same.
String forms[] = (String [])formsVector.toArray();
String forms[] = (String [])formsVector.toArray( new
String[0] );The difference lies in the type of the object returned from toArray. The first form you list, formsVector.toArray(), always returns an Object[]. In your example, you'll get a ClassCastException at runtime when you cast to String[].
The second form will try to use the array you pass in. If it's not big enough, it'll create a new one of the same type as that array. This is what's happening when passing a zero-length array into toArray.
My personal preference is to save an extra instantiation and build the array to the proper size to begin with:String forms[] = (String [])formsVector.toArray( new String[formsVector.size()] ); -
PL/SQL CLOB and comma seperated list
Hi,
i´am beginner!
I have a table with a clob field with a comma separeted list. The content can be '', '44' or '44,55...' as an example.
So how can i get the values in clob and search another table?
Something like...
select clob from table1
each clob
select * from table2
where table2.id = (clob value)
... do somtheing further
Thank you,
JochenOk... it depends...
If you know your CLOB is going to hold a list of values that are less than 4000 characters, you can simply treat the CLOB as a VARCHAR2 and perform one of the many techniques for splitting that string to give a varying IN list...
e.g.
SQL> ed
Wrote file afiedt.buf
1 select *
2 from emp
3 where ename in (
4 with t as (select '&input_string' as txt from dual)
5 select REGEXP_SUBSTR (txt, '[^,]+', 1, level)
6 from t
7 connect by level <= length(regexp_replace(txt,'[^,]*'))+1
8* )
SQL> /
Enter value for input_string: SCOTT,JAMES
old 4: with t as (select '&input_string' as txt from dual)
new 4: with t as (select 'SCOTT,JAMES' as txt from dual)
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7788 SCOTT ANALYST 7566 19-04-1987 00:00:00 3000 20
7900 JAMES CLERK 7698 03-12-1981 00:00:00 950 30
SQL>(or alternatively read here: http://tkyte.blogspot.com/2006/06/varying-in-lists.html)
If it's going to exceed the SQL VARCHAR2 limit of 4000 characters then you would most likely need to create a Pipelined function to split your CLOB into it's component values and return each one, thus allowing you to treat the results as a table of their own... e.g.
Note: this example is for a pipelined function that splits a varchar2 string, but you could adapt it to use the DBMS_LOB package to split a CLOB in the same manner...
SQL> CREATE OR REPLACE TYPE split_tbl IS TABLE OF VARCHAR2(4000);
2 /
Type created.
SQL> CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_delim VARCHAR2:=' ') RETURN SPLIT_TBL PIPELINED IS
2 l_idx PLS_INTEGER;
3 l_list VARCHAR2(4000) := p_list;
4 l_value VARCHAR2(4000);
5 BEGIN
6 LOOP
7 l_idx := INSTR(l_list, p_delim);
8 IF l_idx > 0 THEN
9 PIPE ROW(SUBSTR(l_list, 1, l_idx-1));
10 l_list := SUBSTR(l_list, l_idx+LENGTH(p_delim));
11 ELSE
12 PIPE ROW(l_list);
13 EXIT;
14 END IF;
15 END LOOP;
16 RETURN;
17 END SPLIT;
18 /
Function created.
SQL> SELECT column_value
2 FROM TABLE(split('FRED,JIM,BOB,TED,MARK',','));
COLUMN_VALUE
FRED
JIM
BOB
TED
MARK
SQL> create table mytable (val VARCHAR2(20));
Table created.
SQL> insert into mytable
2 select column_value
3 from TABLE(split('FRED,JIM,BOB,TED,MARK',','));
5 rows created.
SQL> select * from mytable;
VAL
FRED
JIM
BOB
TED
MARK
SQL>... and once you can treat the values like a table it's just a case of using it like you would any table of values i.e. join on it or use it in an IN statment with a subselect etc. -
How to Pass String array from Java to PL/SQL and this use in CURSOR
hi,
I cant understand how to pass Array String as Input Parameter to the Procedure and this array use in Cursor for where condition like where SYMPTOM in( ** Array String **).
This array containing like (SYMPTOM ) to be returned from the java to the
pl/sql (I am not querying the database to retrieve the information).
I cannot find an example on this. I will give the PL/SQL block
create or replace procedure DISEASE_DTL<*** String Array ***> as
v_SYMPTOM number(5);
CURSOR C1 is
select distinct a.DISEASE_NAME from SYMPTOM_DISEASE_RD a
where ltrim(rtrim(a.SYMPTOM)) in ('Fever','COUGH','Headache','Rash') ------- ***** Here use this array element(like n1,n2,n3,n4,n5..) ******
group by a.DISEASE_NAME having count(a.DISEASE_NAME) > 3 ----------- ***** 3 is no of array element - 1 (i.e( n - 1))*****
order by a.DISEASE_NAME ;
begin
for C1rec IN C1 loop
select count(distinct(A.SYMPTOM)) into v_SYMPTOM from SYMPTOM_DISEASE_RD a where A.DISEASE_NAME = C1rec.DISEASE_NAME;
insert into TEMP_DISEASE_DTLS_SYMPTOM_RD
values (SL_ID_SEQ.nextval,
C1rec.DISEASE_NAME,
(4/v_SYMPTOM), --------**** 4 is no of array element (n)************
(1-(4/v_SYMPTOM)));
end loop;
commit;
end DISEASE_DTL;
Please give the proper solution and step ..
Thanking you,
AsishI've haven't properly read through your code but here's an artificial example based on a sql collection of object types - you don't need that, you just need a type table of varchar2 rather than a type table of oracle object type:
http://orastory.wordpress.com/2007/05/01/upscaling-your-jdbc-app/ -
Count the number of elements in comma seperated list of values
Hello Friends,
I have a string with comma seperated list of values say
String v = 34343,erere,ererere,sdfsdfsdfs,4454,5454,dsfsdfsfsd,fsdfsdfsdfs,dfdsfsdfsdfs,sdsfdsf,ererdsdsd45454,fsdfsdfs
Want to count how many elements are existing in this string .
Thanks/KumarHi, Kumar,
REGEXP_COUNT, which Hoek used, is handy, but it only works in Oracle 11. Which version of Oracle are you using?
In any version of Oracle, you can count the commas by seeing how much the string shrinks when you remove them.
LENGTH (str) + 1 - LENGTH (REPLACE (str, ',')) Can str have multiple commas in a row? What if there's nothing between consecutive commas, or nothing by whitespace? Can str begin or end with a comma? Can str consist of nothing but commas? Depending on your answers, you may have to change things. You might want
REGEXP_COUNT ( str
, '[^,]+'
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using.
See the forum FAQ {message:id=9360002} -
Problem using comma separated list with nested table element
Hi,
I have a comma separated list like that:
H23004,H24005,T7231,T8231,T9231And want to create a function which is creating a where clause for each element with an output like that:
UPPER('H23004') IN (UPPER(charge))
OR UPPER('H23005') IN (UPPER(charge))
OR UPPER('T7231') IN (UPPER(charge))
OR UPPER('T8231') IN (UPPER(charge))
OR UPPER('T9231') IN (UPPER(charge))Here is my test function which doesn't work correctly:
create or replace function FNC_LIST_TO_WHERE_CLAUSE(v_list in VARCHAR2) return varchar2 is
-- declaration of list type
TYPE batch_type IS TABLE OF pr_stamm.charge%TYPE;
-- variable for Batches
v_batch batch_type := batch_type('''' || replace(v_list,',',''',''') || '''');
return_script varchar2(1000);
BEGIN
-- loop as long as there are objects left
FOR i IN v_batch.FIRST .. v_batch.LAST
LOOP
--DBMS_OUTPUT.PUT_LINE(offices(i));
-- create where clause
IF i = 1 THEN
return_script := 'UPPER(' || v_batch(i) || ') IN (UPPER(charge))';
ELSE
return_script := return_script || ' OR UPPER(' || v_batch(i) || ') IN (UPPER(charge))';
END IF;
END LOOP;
return (return_script);
end;The out put looks like that:
UPPER('H23004','H24005','T7231','T8231','T9231') IN (UPPER(charge))I have no idea what I do wrong? It calculates the amount of array element wrong! (v_batch.LAST should be 5.)
v_batch.FIRST = 1
v_batch.LAST = 1
Regards,
Tobiastry this....
declare
text varchar2(1000) := 'H23004,H24005,T7231,T8231,T9231';
v_where varchar2(1000);
begin
text := text||',';
while instr(text,',') <> 0
loop
v_where := v_where || 'UPPER('''||substr(text,1,instr(text,',',1)-1)||''' IN (UPPER(charge)) OR ';
text := substr(text,instr(text,',',1)+1);
end loop;
v_where := substr(v_where,1,length(v_where)-3);
dbms_output.put_line(v_where);
end;
convert this one into function ... -
External java function that should return String array
Hi everyone,
I have a split function in plsql that takes 10 times longer a java tokenizer function that i was written. So, i want to use java external function to split my plsql strings into pieces.
I can write a java external procedure that returns types like int, float and String types. I have no problem about it.
My problem is returning an array of strings. I found a book that has an example about how can we get directory list in plsql with java external procedure.
(code)
import java.io.File;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.*;
public class JFile {
public static oracle.sql.ARRAY dirlist (String dir)
throws java.sql.SQLException
Connection conn = new OracleDriver().defaultConnection( );
ArrayDescriptor arraydesc =
ArrayDescriptor.createDescriptor ("DIRLIST_T", conn);
File myDir = new File (dir);
String[] filesList = myDir.list( );
ARRAY dirArray = new ARRAY(arraydesc, conn, filesList);
return dirArray;
CREATE OR REPLACE FUNCTION dirlist (dir IN VARCHAR2)
RETURN dirlist_t
AS
LANGUAGE JAVA
NAME 'myFile.dirlist(java.lang.String) return oracle.sql.ARRARY';
(code)
I could compile this source file in localhost but not remotehost. There are jar files ( import oracle.sql.*; import oracle.jdbc.*; ) that should be added to remote classpath. ( others have already added java classpath ). But, which classpath i should add? Oracle has own JVM and Classpath, probably i should upload these jar files to oracle classpath. Am i wrong? How can i do? Can you explain in detail? How can i return string array from java external function in Oracle ?
I am using Oracle 11.1.0.7 on Solaris Sparc Machine.Hi,
What do you mean "compile in remote host"
Aren't you using the loadjava tool? - that should be enough, the RDBMS already "has" the jars needed.
[A must read|http://download.oracle.com/docs/cd/B28359_01/java.111/b31225/chone.htm#BABCFIIF]
Regards
Peter -
Sorry, if my question is too wordy.
First, the problem -- I am reading integers into my application and converting the those into strings using valueOf(). I then need to use those strings in a switch statment. The only way I could figure how to do this was to use the same String variable in each switch statement but change the the message to fit each case. My professor suggested I use an array list instead.
Second, the question -- how can I convert the String I have generated into a String Array and use the indexing of the array to correspond to the specific text for each case?
Thank you.indeed, you can't use the switch mechanism on strings.
but, if the requirement is that you convert an integer into a string and then switch on those (I don't know why...) from an array of the values, swap the String value back into an int and switch from there. -
Hello everybody,
if I have a string array of say 10 elements, how would I go about shifting those elements to the right or left by one place, ensuring that what had shifted off either end of the array would "wrap around" to the other end of the array?
Thank you for your help in this.
regards,
THE_TH1NGYou could use Arrays.asList() to wrap your array in a list.
To rotate to the right, remove the last element of the list, and add it to the front of the list.
To rotate to the left remove the first element, and add it to the end.
The changes made via the list are written through to the original array you had.
Alternatively write a couple of methods that will do it by hand.
1) store a reference to the array element that will wrap.
2) loop through the elements in the array, copying them into the next element up/down as appropriate.
3) put the stored element back at the start/end of the array as appropriate. -
Suppliers is a field containing a comma delimited list of
Supplier ID's.
When a supplier logs in they should be able to view all the
auctions that they have been registered for
i.e if their supplierID is in the suppliers field.
have tried this and get an error:
<CFQUERY NAME="GetAuctions"
DATASOURCE="#Application.Datasource#">
SELECT * FROM Auctions
WHERE '#Session.SupplierID#' IN 'Auctions.Suppliers'
</CFQUERY>
have tried this and recordcount is 0 when it should be 3:
<CFQUERY NAME="GetAuctions"
DATASOURCE="#Application.Datasource#">
SELECT * FROM Auctions
WHERE '#Session.SupplierID#' LIKE 'Auctions.Suppliers'
</CFQUERY>You should avoid having a list value in a field and normalise
your table. But if you want to stick with your style(which is not
advisable), maybe you can do this. I believe your supplier id is a
string so the code below may cause slowness in your system:
<CFQUERY NAME="GetAuctions1"
DATASOURCE="#Application.Datasource#">
SELECT Suppliers FROM Auctions
</CFQUERY>
<cfoutput query="GetAuctions1">
<CFQUERY NAME="GetAuctions2"
DATASOURCE="#Application.Datasource#">
SELECT * FROM Auctions
WHERE '#Session.SupplierID#' IN(<cfqueryparam
values="#Suppliers#" cfsqltype="CF_SQL_VARCHAR" list="Yes">)
</CFQUERY>
</cfoutput>
But if your supplier id is a numeric value. then you can do
this:
<CFQUERY NAME="GetAuctions"
DATASOURCE="#Application.Datasource#">
SELECT A1.* FROM Auctions A1
WHERE #Session.SupplierID# IN(SELECT A2.Suppliers FROM
Auctions A2 WHERE A2.your_primary_key_for_table_Auctions =
A1.your_primary_key_for_table_Auctions)
</CFQUERY> -
How do I strip off a time format off of a string array
How do I strip off a the first part of a time format out of a string array. The following is what it looks like
14 April 2008 10:00:00.000, 30.000,128.591,-145.839
" " " 10:00:01.000, " " "
I tried the read from speadsheet file first. I tried lower level VIs. There must be something simple I am just missing.Search for the first comma and take the data before it.
Message Edited by Ravens Fan on 12-10-2008 04:50 PM
Attachments:
Example_VI_BD.png 2 KB -
I use the following code to populate a string array:
File dirFile = new File("C:\\somedir");
String fileImport[] = dirFile.list();
This gives me a string array with a whole bunch of files in the following format:
XXXDDMMYYHHMISS.xml
What I need to know is what is the easiest way to sort this array based on this date format, or any date format, in the ascending order, so that when I am loading my XML files, I get the oldest one first.
Appreciate any input.
SamUse the String name of the file (the Date part), together with a java.text.SimpleDateFormat object to parse() the String. You have to set the formatter with a pattern - these are explained fully in the Javadocs for the SimpleDateFormat class. After parsing, you will have java.util.Date objects for each of the files - you can then use these as keys in a java.util.SortedMap (the values would be the files) - the natural ordering of dates will ensure that they are ordered appropriately
Maybe you are looking for
-
App updates are stuck on installing, won't update
I have 10 apps to update. They are all stuck on installing. Have rebooted,doesn't do anything. I can't use the apps either. any suggestions?
-
Weird Error Printing Booklet (PDF)
Please, can anyone help me? I've always used the Print Booklet function and it always worked fine. One day i opened a file that was made on Windows, on the Mac at work and when tried to Print Booklet, it printed on InDesign and then it went to Acroba
-
Hello All, How can I copy my PRODUCTION server data to DEVELOPMENT server. Prd Server System Information. Database: Maxdb 7.5 Operating system: Win 2k3 SP2 Database size : 57GB Development server has same configuration of PRD server should i directly
-
when opening an email its fine but when i try to open inside the email ~ it takes me straight the the apple app something silly i`m not doing what is it please
-
Confused on consolidating/migrating data
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production| PL/SQL Release 11.2.0.3.0 - Production| CORE 11.2.0.3.0 Production| TNS for Solaris: Version 11.2.0.3.0 - Production| NLSRTL Version 11.2.0.3.0 - Production| I have a