Concatenate result set into a string SQL
Hi, I need some help with concatenating a resultset to avoid duplication of data.
I have 3 tables:
SCRIPT
ID - Number PK
DATE - Date
TITLE - Varchar2
AUTHOR
A_ID - Number PK
A_Name - Varchar2
SCRIPT_AUTHOR
ID - Number - PK, FK to Script.ID
A_ID - Number PK, FK to Author.A_ID
I need to list all authors for each script on one line, at the moment I have the following SQL :
Select S.Title, SA.A.ID
FROM SCRIPT S, SCRIPT_AUTHOR SA
WHERE SCRIPT.ID = SCRIPT_AUTHOR.ID
and as expected this is returning a dataset as follows - giving me 2 lines in this case for one script :
S.TITLE, SA.A_ID
1, 1
1, 2
What I am actually after is a result set that combines both the authors in this case in one record: 1, 1:2 so I only have 1 line per script.
The scripts can have many authors, and I will want to do this for many scripts at a time.
I have hit a blank on how to do this, is it possible to do this with SQL?
Many Thanks
p.s. Using: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0
Hi,
That's called "String Aggregation"
[AskTom.oracle.com|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] shows several different ways to do it.
I recommend the first one, the user-defined function STRAGG, which you can copy from that page.
Once you have STRAGG installed, your query is simply
Select S.Title
, STRAGG (SA.A.ID) AS sa_id_list
FROM SCRIPT S
, SCRIPT_AUTHOR SA
WHERE SCRIPT.ID = SCRIPT_AUTHOR.ID
GROUPB BY s.Title;On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
WM_CONCAT is not documented, so you may not want to use it in your Production applications.
Similar Messages
-
So I have a chunk of data that only resides in Oracle. So I need to capture that information from Oracle. Now before you get over zealous, I did try with an OPENQUERY and it took FOREVER! And I don't know why the OPENQUERY took FOREVER but if I run the same
query directly against Oracle it runs very quickly...like 20 seconds.
So now I'm wondering...can I build a dataset in my SSRS Report that uses an Oracle Data source and an Oracle Stored Procedure in its Dataset that I'll create to aggregate this subset of data and then utilize its result set back in my main reporting
Dataset that will utilize SQL Server? And how can I do that? Can I make my main Dataset reference, say, a #TemporaryTable that is created from my Oracle Dataset in its
I'll continue to Google a few things as I await your review and hopefully a reply.
Thanks in advance for your help.Hi ITBobbyP,
According to your description you want to use data from a Oracle data source into a DataSet which retrieving data from SQL Server. Right?
In Reporting Services, we can have multiple data sources in one project pointing to different database. And we can use separated dataset to retrieve data from different data source. However, it's not supported to combine the two datasets together
directly. We can only use Lookup(), LookupSet() function to combine fields from different dataset into one tablix when there are common columns between two datasets. This is the only way to make tow result sets together in SSRS.
Reference:
Lookup Function (Report Builder and SSRS)
LookupSet Function (Report Builder and SSRS)
Best Regards,
Simon Hou
TechNet Community Support -
What is the best way of converting everything in a result set into a string
hello folks
What do you think is the best way of converting everything in a resultset into a string???
At the moment I'm using
rs.getString(i);
everywhere (no matter if the underlying datatype is a date or whatever..) it converts automatically evertything expect NULL into a valid string.
Are there better (simple to use..) ways?I don't see a big switch construct. How about trying the following:
Call this method from your original method by passing the resultset obtained.
public String[] convert(ResultSet rs) {
int col = ((ResultSetMetaData) rs.getMetaData()).getColumnCount();
String[] record = new String[col];
int i=0;
while(rs.next()) {
if(rs.wasNull()) record[i] = new String();
else record[i] = rs.getString(i);
i++;
return record;
iDriZ -
Convert result set into input stream
Hi,
I have result set with me having 93 columns with 1 lac rows. I want to download the result set as xls file.
Because of the data set size is large, i'm not able to hold the data in java object. So i'm trying to convert result set to input stream and giving this input stream to servlet output stream by specifying the contentType as text/xls.
I'm not able to convert result set into input stream.
Could you provide a solution here...
Thanks,
Rajesh1 - JDBC is the wrong way to extract this data. It's like "What's the fastest way
to copy the Oxford English Dictionary using tweets?" I would research the
DBMS's bulk extract functionality.
2 - Are you dead-set absolutely sure you need to do this at all? What can you
do with the data all in one flat file that you cannot do with SQL access to the
data?
3 - If you want to convert all the columns into one (not that it's a huge
win or anything), you can use the DBMS's conversion and concatenation
functionality in your SQL. So instead of
"select col1, col2, col3, .... from MyBigTable"
do (change this to whatever conversion function syntax and concat syntax your DBMS needs)
"select convert(col1, varchar) concat ' ' concat convert(col2, varchar) concat ' ' concat convert(col3, varchar) ... from MyBigTable"
so the result set you get is a single column.
Joe -
Concatenate multiple columns into one string
Hello,
I am using Oracle 11.2, how can I concatenate the value of multiple columns into one string with one SQL:
create table testTb(classId number(5), classRoom varchar2(32));
insert into testTb value(101, 'room101');
insert into testTb value(101, 'room201');
insert into testTb value(101, 'room301');
insert into testTb value(202, 'room444');
insert into testTb value(202, 'room555');
I would like to generate the result as followings:
Class 101 is in room101, room201, room301
Class 202 is in room444, room555
Thanks,Hi,
Since you're using Oracle 11.2, you can use the aggregate LISTAGG function:
SELECT 'Class ' || classid
|| ' is in '
|| LISTAGG ( classroom
) WITHIN GROUP (ORDER BY classroom)
AS txt
FROM testtb
GROUP BY classid
;The generic name for concatenating all the strings in a group is String Aggregation . This page shows several ways to do it, suitable for different versions of Oracle. -
Stepping through a query result set, replacing one string with another.
I want to write a function that replaces the occurance of a string with another different string. I need it to be a CF fuction that is callable from another CF function. I want to "hand" this function an SQL statement (a string) like this: (Please note, don't bother commenting that "there are eaiser ways to write this SQL..., I've made this simple example to get to the point where I need help. I have to use a "sub_optimal" SQL syntax just to demonstrate the situation)
Here is the string I want to pass to the function:
SELECT
[VERYLONGTABLENAME].FIRST_NAME,
[VERYLONGTABLENAME].LAST_NAME,
[VERYLONGTABLENAME].ADDRESSS
FROM
LONGTABLENAME [VERYLONGTABLENAME]
Here is the contents of the ABRV table:
TBL_NM, ABRV <!--- Header row--->
VERYLONGTABLENAME, VLTN
SOMEWHATLONGTALBENAME, SLTN
MYTABLENAME, MTN
ATABLENAME, ATN
The function will return the original string, but with the abreviations in place of the long table names, example:
SELECT
VLTN.FIRST_NAME,
VLTN.LAST_NAME,
VLTN.ADDRESSS
FROM
LONGTABLENAME VLTN
Notice that only the table names surrounded by brackets and that match a value in the ABRV table have been replaced. The LONGTABLENAME immediately following the FROM is left as is.
Now, here is my dum amatuer attempt at writing said function: Please look at the comment lines for where I need help.
<cffunction name="AbrvTblNms" output="false" access="remote" returntype="string" >
<cfargument name="txt" type="string" required="true" />
<cfset var qAbrvs=""> <!--- variable to hold the query results --->
<cfset var output_str="#txt#"> <!--- I'm creating a local variable so I can manipulate the data handed in by the TXT parameter. Is this necessary or can I just use the txt parameter? --->
<cfquery name="qAbrvs" datasource="cfBAA_odbc" result="rsltAbrvs">
SELECT TBL_NM, ABRV FROM BAA_TBL_ABRV ORDER BY 1
</cfquery>
<!--- I'm assuming that at this point the query has run and there are records in the result set --->
<cfloop index="idx_str" list="#qAbrvs#"> <!--- Is this correct? I think not. --->
<cfset output_str = Replace(output_str, "#idx_str#", ) <!--- Is this correct? I think not. --->
</cfloop> <!--- What am I looping on? What is the index? How do I do the string replacement? --->
<!--- The chunck below is a parital listing from my Delphi Object Pascal function that does the same thing
I need to know how to write this part in CF9
while not Eof do
begin
s := StringReplace(s, '[' +FieldByName('TBL_NM').AsString + ']', FieldByName('ABRV').AsString, [rfReplaceAll]);
Next;
end;
--->
<cfreturn output_txt>
</cffunction>
I'm mainly struggling with syntax here. I know what I want to happen, I know how to make it happen in another programming language, just not CF9. Thanks for any help you can provide.RedOctober57 wrote:...
Thanks for any help you can provide.
One:
<cfset var output_str="#txt#"> <!--- I'm creating a local
variable so I can manipulate the data handed in by the TXT parameter.
Is this necessary or can I just use the txt parameter? --->
No you do not need to create a local variable that is a copy of the arguments variable as the arguments scope is already local to the function, but you do not properly reference the arguments scope, so you leave yourself open to using a 'txt' variable in another scope. Thus the better practice would be to reference "arguments.txt" where you need to.
Two:
I know what I want to happen, I know how to make it happen in another programming language, just not CF9.
Then a better start would be to descirbe what you want to happen and give a simple example in the other programming language. Most of us are muti-lingual and can parse out clear and clean code in just about any syntax.
Three:
<cfloop index="idx_str" list="#qAbrvs#"> <!--- Is this correct? I think not. --->
I think you want to be looping over your "qAbrvs" record set returned by your earlier query, maybe.
<cfloop query="qAbrvs">
Four:
<cfset output_str = Replace(output_str, "#idx_str#", ) <!--- Is this correct? I think not. --->
Continuing on that assumption I would guess you want to replace each instance of the long string with the short string form that record set.
<cfset output_str = Replace(output_str,qAbrs.TBLNM,qAbrs.ABRV,"ALL")>
Five:
</cfloop> <!--- What am I looping on? What is the index? How do I do the string replacement? --->
If this is true, then you are looping over the record set of tablenames and abreviations that you want to replace in the string. -
Put database result set into a vector?
I have a resultset rs I would like to put into a vector but I don't seem to get something fundamental. I can put individual items in with add() for instance but how do I dump a whole result set in there...
and if I do so should I turn them all to strings before putting them into the vector?
Any general advice would be appreciated, I've read a lot about Vectors today and have ended up more confused than I'd have expected. So I have come to seek some basic advice.
private static void showResult (ResultSet rs) throws SQLException {
Vector vector = new Vector();
try
// rs is the resultset output from a database
vector.addAll(rs);
catch(NullPointerException ex)
System.out.println("bugger - null pointer exception");
System.out.println();
ex.printStackTrace();
}Iterate over the resultset, create your own object to store data for each row and add that object to the vector. There is no escape from this.
catch(NullPointerException ex)You should not be handling Runtime exceptions. You need to take care not to let them occur through your coding logic. -
Exporting query result set into CSV file using Forms
Hi ,
My requirement is
-> I need to create a form where I have a Multi line text box and two button.
-> When I enter a query in text box and click on Execute button, It should execute a select query.
-> After execution, Result set needs to be exported into an Excel file.
Please give a hint how to do this????
Thanks,
maddyas you are using text item to write SQL query by the user
so for that you need to use the exec_sql package to parse the text items query and get definitions and values of the columns being
resulted in the result set of the query.
once your query is execute to the desired connection then you need to use fetch the result to the CSV file by use of the TEXT_io package
which will open the text file with .csv extension and you have to pass the each line to that text file with comma separated values as "ss","rr" etc.
or you can use the ole2 package to call the excel application and then fetch the data of exe_sql query to that. -
Hello,
I am trying to make stored procedure in what i am getting i_group_id as a list of groups seprated by semicoln like 1,2,14,17,23.
And i want list of emails based on that group. And result set will be as a list of emails seprated by semicolon.
If you know how to install that in stored procedure please help me. Appreciate your help.
Thanks.
PROCEDURE get_groups_email(i_group_id IN VARCHAR2,
x_group_email_dtl_cur OUT resultcur)
IS
x_group_email VARCHAR2(4000):=NULL;
BEGIN
FOR i IN (SELECT TRIM(emp.email) email
FROM ems.employee emp,
ems.groups_employee egrp
WHERE egrp.group_id IN (i_group_id)
AND emp.person_id = egrp.person_id) LOOP
x_group_email:= x_group_email || i.email ||';';
END LOOP;
x_group_email := RTRIM(x_group_email,';');
OPEN x_group_email_dtl_cur FOR
SELECT x_group_email
FROM DUAL;
DBMS_OUTPUT.PUT_LINE('x_group_email:' || x_group_email);
END get_groups_email;
PROCEDURE get_groups_email(i_group_id IN VARCHAR2,
x_group_email_dtl_cur OUT resultcur)
IS
x_group_email VARCHAR2(4000):=NULL;
BEGIN
FOR i IN (SELECT TRIM(emp.email) email
FROM ems.employee emp,
ems.groups_employee egrp
WHERE egrp.group_id IN (i_group_id)
AND emp.person_id = egrp.person_id) LOOP
x_group_email:= x_group_email || i.email ||';';
END LOOP;
x_group_email := RTRIM(x_group_email,';');
OPEN x_group_email_dtl_cur FOR
SELECT x_group_email
FROM DUAL;
DBMS_OUTPUT.PUT_LINE('x_group_email:' || x_group_email);
END get_groups_email;1013527 wrote:
I am using Oracle 9.7.2. Not 11g.
No Database at hand to provide a working example.
So use http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:73830657104020 to split your list into rows.
Join that to your table of e-mail addresses
then take a look at http://www.sqlsnippets.com/en/topic-11787.html maybe chosing http://www.sqlsnippets.com/en/topic-12087.html
and you're done.
Regards
Etbin
something to play with (still NOT TESTED!)
with
e_mails as
(select 1 user_id,'alpha' || chr(64) || 'domain.eu' e_mail from dual union all
select 2,'beta' || chr(64) || 'domain.eu' from dual union all
select 3,'gamma' || chr(64) || 'domain.eu' from dual union all
select 4,'delta' || chr(64) || 'domain.eu' from dual union all
select 5,'epsilon' || chr(64) || 'domain.eu' from dual union all
select 6,'zeta' || chr(64) || 'domain.eu' from dual union all
select 7,'eta' || chr(64) || 'domain.eu' from dual union all
select 8,'theta' || chr(64) || 'domain.eu' from dual union all
select 9,'iota' || chr(64) || 'domain.eu' from dual union all
select 10,'kappa' || chr(64) || 'domain.eu' from dual union all
select 11,'lambda' || chr(64) || 'domain.eu' from dual union all
select 12,'mu' || chr(64) || 'domain.eu' from dual union all
select 13,'nu' || chr(64) || 'domain.eu' from dual union all
select 14,'xi' || chr(64) || 'domain.eu' from dual union all
select 15,'omicron' || chr(64) || 'domain.eu' from dual union all
select 16,'pi' || chr(64) || 'domain.eu' from dual union all
select 17,'rho' || chr(64) || 'domain.eu' from dual union all
select 18,'sigma' || chr(64) || 'domain.eu' from dual union all
select 19,'tau' || chr(64) || 'domain.eu' from dual union all
select 20,'upsilon' || chr(64) || 'domain.eu' from dual union all
select 21,'phi' || chr(64) || 'domain.eu' from dual union all
select 22,'chi' || chr(64) || 'domain.eu' from dual union all
select 23,'psi' || chr(64) || 'domain.eu' from dual union all
select 24,'omega' || chr(64) || 'domain.eu' from dual
groups as
(select 1 g_id,'1,15,21,17' members from dual union all
select 2,'23,10,3,20,7,23,15,9' from dual union all
select 3,'3,4,5,6,7,8' from dual union all
select 4,'23,24,15,16,7,18' from dual
select g_id,
substr(sys_connect_by_path(e_mail,';'),2) e_mail_list
from (select g.g_id,
e.e_mail,
row_number() over (partition by g.g_id order by e.user_id) rn
from e_mails e,
groups g
where instr(','||g.members||',',','||to_char(e.user_id)||',') > 0
and instr(','||:group_list||',',','||to_char(g.g_id)||',') > 0
where connect_by_isleaf = 1
start with rn = 1
connect by rn = prior rn + 1
and g_id = prior g_id
Message was edited by: Etbin provided a small example -
Hello,
I am trying to make stored procedure in what i am getting i_group_id as a list of groups seprated by semicoln like 1,2,14,17,23.
And i want list of emails based on that group. And result set will be as a list of emails seprated by semicolon.
Can anybody please help me for that. Thanks in advance.
PROCEDURE get_groups_email(i_group_id IN VARCHAR2,
x_group_email_dtl_cur OUT resultcur)
IS
x_group_email VARCHAR2(4000):=NULL;
BEGIN
FOR i IN (SELECT TRIM(emp.email) email
FROM ems.employee emp,
ems.groups_employee egrp
WHERE egrp.group_id IN (i_group_id)
AND emp.person_id = egrp.person_id) LOOP
x_group_email:= x_group_email || i.email ||';';
END LOOP;
x_group_email := RTRIM(x_group_email,';');
OPEN x_group_email_dtl_cur FOR
SELECT x_group_email
FROM DUAL;
DBMS_OUTPUT.PUT_LINE('x_group_email:' || x_group_email);
END get_groups_email;
PROCEDURE get_groups_email(i_group_id IN VARCHAR2,
x_group_email_dtl_cur OUT resultcur)
IS
x_group_email VARCHAR2(4000):=NULL;
BEGIN
FOR i IN (SELECT TRIM(emp.email) email
FROM ems.employee emp,
ems.groups_employee egrp
WHERE egrp.group_id IN (i_group_id)
AND emp.person_id = egrp.person_id) LOOP
x_group_email:= x_group_email || i.email ||';';
END LOOP;
x_group_email := RTRIM(x_group_email,';');
OPEN x_group_email_dtl_cur FOR
SELECT x_group_email
FROM DUAL;
DBMS_OUTPUT.PUT_LINE('x_group_email:' || x_group_email);
END get_groups_email;>
Can anybody please help me for that
>
Not in this forum they can't. This forum, as the title says, is for SQL Developer questions only.
Please mark this question ANSWERED and repost it in the SQL and PL/SQL forum
https://forums.oracle.com/community/developer/english/oracle_database/sql_and_pl_sql -
Problems in mapping a result set into IN operator
i can't for the life of me figure out how to create the following predicate in a mapping:
WHERE table1.cola NOT IN (SELECT table2.cola
FROM table2);Chris,
Perhaps you can use the minus operator in your example. I.e.:
select table1.cola
minus
select table2.cola
This select would result in the set of data you need.
Mark. -
How display result set of a PL/ SQL function call in a dialog box
Hello,
I am calling a PL/ SQL function from Apex, which returns - List of varchar.
In Apex, it should show this list of varchar and "Yes" and "No" buttons on a message window.
Can you please suggest a way to achieve the same.
Thanks,
GirishHello,
This application process "vrl_popup" is to get the values from PL/ SQL function. For popup window - confirm(). Also declared the LV_list as Application Item.
Which is coded in the region part of the button. After pressing this button popup window should come with the list.
<script type="text/javascript">
<!--
function doAjaxRequestParam( process, parameter)
var ajaxRequest = new htmldb_Get(null,&APP_ID.,'vrl_popup='+process,0);
ajaxRequest.add('lv_list', parameter );
var jsonResult = eval('('+ ajaxRequest.get() +')');
return jsonResult;
var answer = confirm ("can try this?")
alert (v_list)
if (answer)
alert ("done")
else
alert ("Unsuccessful")
// -->
</script>
In apex I created following Application process by name = vrl_popup,
declare
lv_List varchar2(2000) := '';
begin
begin
lv_List := select vrl_type_process_pkg.get_regd_reg_lste() from dual;
exception when no_data_found then null;
end;
htp.prn(lv_List);
end;
Kindly help in fixing this.
Edited by: Girish on Jun 17, 2010 12:57 AM -
How to split a result set into n-number ranges, each range has same max-min
Hi guys,
suppose there's a table T1(fvalue number),
we can easily get the MAX and MIN of fvalue, for example, 19 and 5, I need to split them into, for example, 3 ranges, 5-9, 10-14, 15-19, they have the same max-min. And for each range, I need to know the count of rows that fall into this range.
does anyone have any clues? is there any analytic function i can use to accomplish this?
many thanks.There are the NTILE and WIDTH_BUCKET functions that may be of use. However, I'm not exactly sure what you are after.
It is always helpful to provide the following:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details. -
JSP Servlet and convert the result set of an SQL Query To XML file
Hi all
I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
thisis my servlet which will call the jsp page and the jsp just behind it.
//this is the servlet
import java.io.*;
import java.lang.reflect.Array;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
public *class *Campaign *extends *HttpServlet
*private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
*private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
*private* DataSource _dataSource;
*public* *void* setDataSource(DataSource dataSource)
_dataSource = dataSource;
*public* DataSource getDataSource()
*return* _dataSource;
*public* *void* init()
*throws* ServletException
*if* (_dataSource == *null*) {
*try* {
Context env = (Context) *new* InitialContext().lookup("java:comp/env");
_dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
*if* (_dataSource == *null*)
*throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
} *catch* (NamingException e) {
*throw* *new* ServletException(e);
protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
Connection conn = *null*;
*try* {
conn = getDataSource().getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
// out.println("Le résultat :<br>");
ArrayList <String> Lescomments= *new* ArrayList<String>();
ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
ArrayList <String> Lesnoms = *new* ArrayList <String>();
*while* (rs.next()) {
Lescomments.add(rs.getString("comments"));
request.setAttribute("comments",Lescomments);
Lesidentifiant.add(rs.getString("post_id"));
request.setAttribute("id",Lesidentifiant);
Lesnoms.add(rs.getString("postname"));
request.setAttribute("nom",Lesnoms);
rs.close();
stmt.close();
*catch* (SQLException e) {
*finally* {
*try* {
*if* (conn != *null*)
conn.close();
*catch* (SQLException e) {
// les paramètres sont corrects - on envoie la page réponse
getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
}///end of servlet
}///this is the jsp page called
<%@ page import="java.util.ArrayList" %>
<%
// on récupère les données
ArrayList nom=(ArrayList)request.getAttribute("nom");
ArrayList id=(ArrayList)request.getAttribute("id");
ArrayList comments=(ArrayList) request.getAttribute("comments");
%>
<html>
<head>
<title></title>
</head>
<body>
Liste des campagnes here i will create the xml file the problem is to display all rows
<hr>
<table>
<tr>
</tr>
<tr>
<td>Comment</td>
<td>
<%
for( int i=0;i<comments.size();i++){
out.print("<li>" + (String) comments.get(i) + "</li>\n");
}//for
%>
</tr>
<tr>
<td>nom</td>
<td>
<%
for( int i=0;i<nom.size();i++){
out.print("<li>" + (String) nom.get(i) + "</li>\n");
}//for
%>
</tr>
<tr>
<td>id</td>
<td>
<%
for( int i=0;i<id.size();i++){
out.print("<li>" + (String) id.get(i) + "</li>\n");
}//for
%>
</tr>
</table>
</body>
</html>
This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
// Identify a carriage return character for each output line
int iLf = 10;
char cLf = (*char*)iLf;
// Create a new empty binary file, which will content XML output
File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
//outputFile.createNewFile();
FileWriter outfile = *new* FileWriter(outputFile);
// the header for XML file
outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
try {
// Define connection string and make a connection to database
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
Statement stat = conn.createStatement();
// Create a recordset
ResultSet rset = stat.executeQuery("Select * From posts");
// Expecting at least one record
*if*( !rset.next() ) {
*throw* *new* IllegalArgumentException("No data found for the posts table");
outfile.write("<Table>"+cLf);
// Parse our recordset
// Parse our recordset
*while*(rset.next()) {
outfile.write("<posts>"+cLf);
outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
outfile.write("</posts>"+cLf);
outfile.write("</Table>"+cLf);
// Everything must be closed
rset.close();
stat.close();
conn.close();
outfile.close();
catch( Exception er ) {
%>Please state your problem that you are having more clearly so we can help.
I looked at your code I here are a few things you might consider:
It looks like you are putting freely typed-in comments from end-users into an xml document.
The problem with this is that the user may enter characters in his text that have special meaning
to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
and re-displayed correctly.
Also, it looks like you are putting business logic in your JSP page (creating an xml file).
The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client. -
Combining result set of two services into one result set
Hi,
I have a model where I am getting one result set (6 Fields) from BI query and another result set (3 Fields which gives real time values) from OLTP system. I want to show the output of these two result sets into single result set (7 Fields). I have a common field in both the result sets as key field.
I tried this using UNION operator but I am not able to set the Key fields and also in the table view of UNION operator I am getting any field to be added to table.
Can anyone help me to solve this problem?
Any help is appreciated.
Regards,
AmitHi Amit,
in this case, you have to use the combine-operator. However, this operator needs a key-field in each of these sets. E.g. Combine set (<u>customer-id</u>, order-id, week, delivery-state) with set (<u>customer-id</u>, city, client-class).
The combine operator might not be available when compiling to webdynpro, I did not check that.
Best Regards, Benni
Maybe you are looking for
-
Single User Mode: Searching for root...
My 2 year old unplugged my PowerMac iMac G5 (single) and now it won't start up. I was finally able to boot up off of Disk Warrior and replace the directory, but it won't start up past the gray Apple screen. The fan comes on after about 45 seconds and
-
Itunes won't open due to audio configuration?
I just got a new Ipod and upgraded from a 30 gig to an 80 gig. The new one would only work on itunes 7.4 or better- so I downloaded it. Now Itunes won't open at all! It says: Itunes cannot run because it has detected a problem with your audio configu
-
Issue with 10.9.2 looking NAS drive away from home network
I have a NAS drive on my home network. When I am away from my home network my MBP running 10.9.2 keeps looking for and not find ing the drive. It keeps interupting my work flow every few minutes. How do I resolve this issue? it is very annoying.
-
With my system, if Dolby Digital is set to "On" in settings, I don't get any sound at all from Rented or Purchased movies from iTunes - however, I do get sound from Netflix, Youtube, iTunes music, etc. Sound works in iTunes material if Dolby Digital
-
Large SolidWorks 2006 assembly
I wanted to insert my u3d. file in microsoft word and then convert it into a pdf file. My u3d file is about 15mb. I am able to insert it in micorsoft word but can't create a pdf file. After starting the conversion it freezes. Is the file to big for a