JSP DataBase Result Not Displaying Properly - mysql

I have a JSP MySQL query
<sql:query var="libraries" dataSource="jdbc/ArabiTagOnline"><br>
SELECT l.LibraryId, v1.LAvalue AS "dbESTid", v2.LAValue AS "LibName", v3.LAValue AS "Desc"
FROM ((Library l LEFT JOIN LibAttrValue v1 ON l.LibraryId = v1.LibraryId AND v1.AttributeId = 1)
LEFT JOIN LibAttrValue v2 ON l.LibraryId = v2.LibraryId AND (v2.AttributeId = 2 OR v2.AttributeId IS NULL))
LEFT JOIN LibAttrValue v3 ON l.LibraryId = v3.LibraryId AND (v3.AttributeId = 6 OR v3.AttributeId IS NULL)
<\sql:query
This returns four columns.
I tried to rename the columns in the results with AS but when iterating over the results
<c:forEach var="libraryResults" items="${libraries.rows}">
<tr>
<td>${libraryResults.Libraryid}</td>
<td>${libraryResults.dbESTid}</td>
<td>${libraryResults.LibName}</td>
<td>${libraryResults.Desc}</td>
</tr>
</c:forEach>
When loading the page, the columns dbESTid, LibName and Desc are blank.
I asked ${libraries.columnNames} and found out the AS statement in my query didn't rename the columns, they are all still LAValue. ${libraryResults.LAValue} only returns Desc. Any help on how I can populate this table?

You don't need double quotes around column aliases in your SQL - that may be confusing the jdbc driver. Also, why the break tag within the <sql-query>?
Column aliasing should work. However, if the problem persists one possible workaround is to iterate over columns within each row:
<c:forEach var="libraryResults" items="${libraries.rows}">
<tr>
<c:forEach var="column" items="${libraryResults}">
<td><c:out value="${column.value}"/></td>
</c:forEach>
</tr>
</c:forEach>
That said, the real solution is, of course, to use an MVC framework so you don't have to embed your queries in JSP.

Related

Values from xml data field in mysql

i would like to know if there is a query to select values from all of my xml data fields. There are around 1k rows which has xml data. All of them has almost the same data structure. With extract value i was able to extract one data field but at the point where more than one row is part of my subquery it breaks.
Here is an example xml data inside my db:
<EDLXML version="1.0.0" type="variable">
<properties id="template_variables">
<deliveredDuration>4444</deliveredDuration>
<deliveredNum>1</deliveredNum>
<comment/>
<projectname>cdfkusen</projectname>
<name>kral_schalke_trenink</name>
<order_id>372846</order_id>
<cutlistId>2763_ID</cutlistId>
<bcutlistId>51ddgf7a6-1268-1gdfged-95e6-5254000e8e1a</bcutlistId>
<num>1</num>
<duration>177760</duration>
<quotaRelevantDuration>0</quotaRelevantDuration>
<organisationUid>OrgName</organisationUid>
<organisationQuota>333221233</organisationQuota>
<organisationUsedQuota>123</organisationUsedQuota>
<organisationContingentIrrelevantQuotaUsed>54</organisationContingentIrrelevantQuotaUsed>
<userDbId>7xxxx84-eb9b-11fdsb-9ddd1-52cccccde1a</userDbId>
<userId>xxxx</userId>
<userRights>RH_DBC</userRights>
<firstName>DThom</firstName>
<lastName>Test</lastName>
<userMail>xxx#ccc.cz</userMail>
<language>English</language>
<orderTimestamp>1659448080</orderTimestamp>
<stitching>false</stitching>
<transcode>NO</transcode>
<destination>Standard</destination>
<collaboration>private</collaboration>
<premiumUser>false</premiumUser>
<priority>normal</priority>
<userMail2>xxx#ccc.cz</userMail2>
<cutlistItems>
<cutListId>125124_KFC</cutListId>
<cutListItemId cutlistItemDeliveryStatus="&#10004" cutlistItemDStatusMessage="delivered">112799</cutListItemId>
<bmarkerId>8f16ff80-1269-11ed-95e6-5254000e8e1a</bmarkerId>
<videoId>2912799</videoId>
<counter>1</counter>
<frameInSpecified>true</frameInSpecified>
<frameIn>15638</frameIn>
<frameOutSpecified>true</frameOutSpecified>
<frameOut>20082</frameOut>
<tcIn>00:10:25:13</tcIn>
<tcOut>00:13:23:07</tcOut>
<duration>177760</duration>
<BroadcastDate>2021-07-24</BroadcastDate>
<eventDate>2021-07-24</eventDate>
<resolutionFacet>HD</resolutionFacet>
<provider>DBC</provider>
<technicalrightholders>RH_DBC</technicalrightholders>
<rights>DBC</rights>
<materialType>DP</materialType>
<targetFilename>kral_schalke_trenink</targetFilename>
</cutlistItems>
</properties>
</EDLXML>
I got the right value from query if i do:
SELECT ExtractValue((SELECT job_xml from cutlist where job_xml is not null LIMIT 1), '//deliveredNum');
But when i change the limit amount i get back: Subquery return more than one row.
extractvalue expects two string arguments. When your subquery returns more than one row, you are not simply passing a string as the first argument (you are passing a set of results).
Instead of calling extractvalue once for your entire query, call it once for every row, like:
SELECT ExtractValue(job_xml, '//deliveredNum')
FROM cutlist
WHERE job_xml IS NOT NULL

SQL Server - transforming a string into JSON Object in routine

I am currently working on a way to get a distribution list for all users registered to our application. We are using a SQL server to store information, however, due to a move to a non-relational DB schema in the near future, most of our data is stored in one field as a JSON string (It's a VARCHAR(max) field that looks like JSON). When we serve this data back to our Java controllers, we convert the String into a JSON Object. As my question would most likely indicate, the list of users is located in this JSON string. While I know I can just do SELECT JSON_DATA FROM MYTABLE to get all entries of this field, convert it in Java, and get the users field that way, I would be essentially returning a TON of data and throwing away 95% of it.
I was wondering if there is a way in SQL Server to parse a JSON string? Essentially what I want to do is with the following table:
<table style="width:100%" border="1">
<tr>
<th>ID</th>
<th>JSON_DATA</th>
</tr>
<tr>
<td>1</td>
<td>{"data":data,"users":["User1", "User2"]}</td>
</tr>
<tr>
<td>2</td>
<td>{"data":data2,"users":["User2", "User3"]}</td>
</tr>
</table>
I want to return from my SQL routine a list of all unique users.
I think this might give you what you need:
Select JSON_QUERY([fieldName], $.users)
Here's a link to check out too: https://learn.microsoft.com/en-us/sql/t-sql/functions/json-query-transact-sql?view=sql-server-2017
Without native JSON support, I'm afraid you're looking a good ol' string parsing. This should get you part of the way: it returns a single string with
"User1", "User2", "User2", "User3"
DECLARE #ThisUserString VARCHAR(255)
, #FullUserString VARCHAR(255) = ''
DECLARE #xmlSTring VARCHAR(MAX) =
'<table style="width:100%" border="1">
<tr>
<th>ID</th>
<th>JSON_DATA</th>
</tr>
<tr>
<td>1</td>
<td>{"data":data,"users":["User1", "User2"]}</td>
</tr>
<tr>
<td>2</td>
<td>{"data":data2,"users":["User2", "User3"]}</td>
</tr>
</table>'
WHILE CHARINDEX('[', #xmlSTring) > 0
BEGIN
-- Find the next set of users, like ["User1", "User2"]
SELECT #ThisUserString =
SUBSTRING(
#xmlSTring
, /*start*/ CHARINDEX('[', #xmlSTring)
, /*length*/ CHARINDEX(']', #xmlSTring) - CHARINDEX('[', #xmlSTring) + 1
)
-- Add them to the list of all users, like "User1", "User2"
SELECT #FullUserString += ', ' +
SUBSTRING(
#xmlSTring
, /*start*/ CHARINDEX('[', #xmlSTring) + 1
, /*length*/ CHARINDEX(']', #xmlSTring) - CHARINDEX('[', #xmlSTring) - 1
)
-- And remove this set from the string so our WHILE loop will end sometime:
SET #xmlSTring = REPLACE(#xmlSTring, #ThisUserString, '')
END
SET #FullUserString = RIGHT(#FullUserString, LEN(#FullUserString) - 2) -- remove the initial comma
SELECT #FullUserString

How to extract all rows with concatenated cells from a table using Xpath?

I have an html table:
<table class="info">
<tbody>
<tr><td class="name">Year</td><td>2011</td></tr>
<tr><td class="name">Storey</td><td>3</td></tr>
<tr><td class="name">Area</td><td>170</td></tr>
<tr><td class="name">Condition</td><td>Renovated</td></tr>
<tr><td class="name">Bathroom</td><td>2</td></tr>
</tbody>
</table>
In this table data is organized in such way that each row contains 2 cells enclosed in <td> tags. First cell contains information about data type. For example year of building of house. Second cell contains year information itself which is 2011.
I want to extract data in such way that data type and information are divided and corresponded to each other. I want to extract data type and information this way:
Year - 2011
Storey - 3
Area - 170
Condition - Renovated
Bathroom - 2
For now I am using Xpath's concatenation function concat. Here is my Xpath expression:
concat(//table[#class="info"]//tr//td[contains(#class, 'name')]/text() , ' - ', //table[#class="info"]//tr//td[not(contains(#class, 'name'))]/text())
This XPath returns this result:
Year - 2011
My table contains 5 rows. My Xpath expression returned only 1st row with concatenated cells.
But 2 Xpath expressions that I send to concat function individually return the normal result with all rows.
These are the 2 XPath expressions:
//table[#class="info"]//tr//td[contains(#class, 'name')]/text()
and
//table[#class="info"]//tr//td[not(contains(#class, 'name'))]/text()
Both of this expressions return all rows with required information. When I send this two expressions to concat function, it returns only the 1st row.
How to get all rows with concatenated cells using Xpath? I guess it is not possible using Xpath only. Do I have to do it with the help of some programming language such as PHP or may be new version of Xpath or some sophisticated expressions can help me in this case?
If you use java:
1 get a Dom document
2 loop
int i=1;
while (true)
{
if (xpath.compile("//tr["+i+"]").evaluate(document,XPathConstants.NODE) ==null) break;
expr = xpath.compile("concat (//tr["+i+"]/td[#class='name']/text(),' - ',//tr["+i+"]/td[not(#class='name')]/text())");
resX= (String) expr.evaluate(document, XPathConstants.STRING);
System.out.println(resX);
i++;
}
Another option:
get every tr
expression="//table[#class=\"info\"]//tr";
XPathExpression expr = xpath.compile(expression) ;
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
and inside
for (int temp1 = 0; temp1 < nodes.getLength(); temp1++) {
Node nodeSegment = nodes.item(temp1);
if (nodeSegment.getNodeType() == Node.ELEMENT_NODE) {
...
expr = xpath.compile("concat (td[#class='name']/text(),' - ',td[not(#class='name')]/text())");
resX= (String) expr.evaluate(eElement, XPathConstants.STRING);
System.out.println(resX);

Linq joined tables in gridview

var result = from p in dc.People
join d in dc.Departments
on p.fk_dep_id equals d.pk_dep_id
select p;
return result.ToList();
The linq query above will select all People, together with the full name of the department they are assigned to. This result contains the Department data in an object "Department", which I can see when debugging.
However, when adding this result to a gridview, the joined data triggers an error:
"A field or property with the name "Department.name" was not found on the selected data source.
I tried doing the following in the Gridview:
<asp:BoudField DataField="Department.Name" HeaderText="Department" SortExpression="Department.Name" />
Any ideas on how to display such a "joined" columns in a Gridview, by using linq2sql data?
The DataField should be a property name of the object in the data source. You can't use complex expressions like that. For this you need the TemplateField:
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server"
Text="<%# (Eval("Department") as Department).Name %>" />
</ItemTemplate>
</asp:TemplateField>

Some HTML/CSS to get around a drawback in Struts2

I am trying to get an HTML page like: http://jsbin.com/awoco.
This is a JSP page so it will include scriptlets. Final HTML output will be kind of like this (tags unclosed to save space):
<%
Iterator it = MyList.iterator()
While (it.hasNext())
SomeClass all = it.next();
SomeClass a = it.next();
SomeClass b = it.next();
%>
<tr>
<td rowspan=3 valign=top>Red<td><%=all.Name()%><td><%=all.price()%><td><%=all.originalPrice()%>
</tr>
<tr>
<td><%=a.Name()%><td><%=a.price()%><td><%=a.originalPrice()%>
</tr>
<tr >
<td><%=b.Name()%><td><%=b.price()%><td><%=b.originalPrice()%>
</tr>
As you can see, I have to call next() 3 times inside the while loop. This is because the source of the data is a List populated that way, and I have to show the data in the exact same manner as in the link provided above.
Is there a way to change the HTML output somehow so that I don't have to call next() more than once, but still get the same table structure?
Change your data structures. MyList should be list of (something like) AgregateClass which will contain 3 members of type SomeClass (all,a,b) and then simply iterate through MyList.
Just few tips:
If you are using Struts2 you can use <s:iterator> tag to iterate through collections. documentation
Since JSP 2.0 or so you can write ${b.price} instead of <%=b.price()%>
You should change tags you added to your question as it has nothing to do with html or css.