Grails not displaying SQL results in table, what am I missing? - sql

I'm obviously missing something obvious here but I cant for the life of me work out what, I've setup a view to display a custom SQL query, but the screen is showing nothing, here's what I've got
Controller
def queueBreakdown(){
String SQLQuery = "select state, count(test_exec_queue_id) as 'myCount' from dbo.test_exec_queue group by state"
def dataSource
def list = {
def db = new Sql(dataSource)
def results = db.rows(SQLQuery)
[results:results]
}
}
If I run this manually I get a set of results back like so
state myCount
1 1
test 2
test2 1
The queueBreakdown.gsp has the following...
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
</ul>
</div>
<div id="queueBreakdown-testExecQueue" class="content scaffold-list" role="main">
<h1><g:message code="Execution Queue Breakdown" /></h1>
<table>
<thead>
<tr>
<g:sortableColumn property="Run State" title="Run State"/>
<g:sortableColumn property="Count" title="Count" />
</tr>
</thead>
<tbody>
<g:each in="${results}" status="i" var="it">
<tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
<td>${it.state}</td>
<td>${it.myCount}</td>
</tr>
</g:each>
</tbody>
</table>
</div>
</body>
But when I view the page I get nothing... The table has been built but there are no lines in it, what am I being thick about here?
Cheers

your controller code is really confusing, what is the action here ? queueBreakdown() or list() ? It seems like you have mixed up 2 actions together, and queueBreakdown() is not returning any model...
class SomeController {
def dataSource
def queueBreakdown() {
String SQLQuery = "select state, count(test_exec_queue_id) as 'myCount' from dbo.test_exec_queue group by state"
def db = new Sql(dataSource)
def results = db.rows(SQLQuery)
[results:results]
}
}

Related

How to match an item in first row of a html table?

This is a snippet of the UI. Let me know to define to using karate automation.
<tr class="row" id="row0">
<td class ="ID1">AXZ123</td>
<td class ="ID2">AXZ456</td>
<td class ="ID3">AXZ789</td>
<input type="radio" "name=radio0">
I want to match AXYZ123 == locateAll("//tr..").
Please let me know the accurate way to define it.
Try this approach: https://github.com/intuit/karate/tree/master/karate-core#tree-walking
* def rows = locateAll('tr')
* def firstRow = rows[0]
* def temp = firstRow.firstChild.text
* print temp
Also refer: https://stackoverflow.com/a/66640025/143475

slicing an html file to pandas dataframe while preserving parent-child relationship of div tags of the format

i'm trying to cut an html file into a dataframe preserving parent child relationship between div tags.
for instance:
<div class="ddemrcontentitem ddremovable" dd:entityid="0" id="_5C026969-
71BA-456E-A183-BC923BAB9E99" style="clear: both;"
xmlns:dd="DynamicDocumentation">Orders:
<div style="padding-left: 8px;">
<div class="ddemrcontentitem ddremovable" dd:contenttype="NONMEDORDERS" dd:entityid="251406974" id="_57B1A3DC-1899-4752-9516-6F137BBE1C8F">CBC w/ Auto Diff</div>
<div class="ddemrcontentitem ddremovable" dd:contenttype="NONMEDORDERS" dd:entityid="251389861" id="_0A418835-4384-4ACC-A4FD-3C901539DADB">Hygiene Activity</div>
<div class="ddemrcontentitem ddremovable" dd:contenttype="NONMEDORDERS" dd:entityid="251389598" id="_5D06090F-7330-49B1-BB53-28496388E8C1">Regular Diet</div>
<div class="ddemrcontentitem ddremovable" dd:contenttype="NONMEDORDERS" dd:entityid="251407213" id="_0D683EC1-4D18-45F4-BD52-0451DDA3BF5A">Sodium Level</div>
<div class="ddemrcontentitem ddremovable" dd:contenttype="NONMEDORDERS" dd:entityid="251410812" id="_82ACC1FF-DA2E-472C-BA0F-E881293BDCBA">Sodium Level</div>
</div>
orders should be parent to each of (CBC w/ Auto Diff,Regular Diet,Sodium Level,Sodium Level) in a dictionary or a dataframe.
this is my failing trial:
import pandas as pd
import bs4
'''i imported the file- parsed html using bs4 package
made a list of the div tags and made 2 dictionary too
one with the text and one with the full tags and text
then made tables of them (pandas dataframes)'''
alpha = open('D://python/893714319.00.html','r')
beta = bs4.BeautifulSoup(alpha, 'lxml')
lister = []
fulllister = []
listerer = {}
mydivs = beta.findAll('div')
for div in mydivs:
lister.append(div.text)
fulllister.append(div.contents)
listerer = {k:v for v,k in enumerate(lister)}
fulllisterer = {k:v for k,v in enumerate(fulllister)}
listerer = sorted(listerer.items(), key=lambda x: x[1])
fulllisterer = sorted(fulllisterer.items(), key = lambda x:x[1])
listerer = pd.DataFrame(listerer)
fulllisterer = pd.DataFrame(fulllisterer)
listerer.dropna( inplace='True',how='any')
fulllisterer.dropna(axis=1, inplace='True',how='any')
'''trying to characterize the string that is parent and what is child
by counting <div> in it but this is not working , i don't know why
by parent i mean 'orders' and the children would be 'cbc' and so
'''
fulllisterer['divier']= ""
fulllisterer['count']= 0
for string in fulllisterer[1].iteritems():
fulllisterer['count']=string.count('<div>')
if string.count('<div>')>1:
fulllisterer['divier'] = fulllisterer[1]
the output would look like:
<html>
<body>
<table>
<th>parent</th>
<th>child</th>
<tr>
<td>orders</td>
<td>CBC w/ Auto Diff</td>
</tr>
<tr>
<td>orders</td>
<td> Hygiene Activity</td>
</tr>
<tr>
<td>orders</td>
<td> Regular Diet</td>
</tr>
<tr>
<td>orders</td>
<td>Sodium Level</td>
</tr>
<tr>
<td>orders</td>
<td>Sodium Level</td>
</tr>
</table>
</body></html>
the output would be like
I think you were just over-engineering this. The following code, adapted from your snippet should do
import pandas as pd
import bs4
beta = bs4.BeautifulSoup(alpha, 'lxml')
mydivs = beta.findAll('div')
lister = []
for div in mydivs:
lister.append(div.text)
data_list = lister[0].split('\n')
data_list = [el.strip().replace(':', '') for el in data_list if el.strip() != '']
df = pd.DataFrame()
print pd.DataFrame({'parent': data_list[0], 'child':data_list[1:]})
Now you just need to make sure this is called for each parent div tag in place of lister[0].

pdo count not working

I have a page and all the function is working my only problem now is ciunying the record from the databse..
Class.user.php
Public function data($count)
{
$stmt=$this->db->prepare("SELECT COUNT(*) FROM login");
$result=$this->db->prepare($count);
$result->execute();
$number_of_rows=$result->fetchColumn();
}
Index.php
<table>
<thead>
<tr>
<th>2014</th>
</tr>
</thead>
<tbody>
<?php
$count="SELECT COUNT(*) FROM login";
$crud->data($count);
?>
The problem is that its not showing the count..
You're writing the same query as function argument, but also inside the function itself. And you're only really using one. This is nonsense. Dedicate your method to return the count, don't make the query a parameter.
prepareing the statement is pointless in this case, since you're neither reusing it nor are you binding any values. You can simply query() it directly.
The clincher: you're neither outputting nor returning the count, so it's very very expected that it doesn't show up anywhere.
Here's a sane version:
public function getCount() {
$result = $this->db->query('SELECT COUNT(*) FROM login');
return $result->fetchColumn();
}
<tbody>
<tr>
<td>
<?php echo $crud->getCount(); ?>
I think I usually do it like this link
$sql= "SELECT COUNT(*) FROM login";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row =$stmt->fetchObject();
then to output it you would have to ECHO
<table>
<tbody>
<tr>
<td>
<?php echo $row['count'];?>
</td>
</tr>
</tbody>
</table>

How to get element with specific value in htmlagilitypack

I have ASP.NET MVC4 project where try to parse html document with HtmlAgilityPack. I have the following HTML:
<td class="pl22">
<p class='pb10 pt10 t_grey'>Experience:</p>
<p class='bold'>any</p>
</td>
<td class='pb10 pl20'>
<p class='t_grey pb10 pt10'>Education:</p>
<p class='bold'>any</p>
</td>
<td class='pb10 pl20'>
<p class='pb10 pt10 t_grey'>Schedule:</p>
<p class='bold'>part-time</p>
<p class='text_12'>2/2 (day/night)</p>
</td>
I need to get values:
"any" after "Experience:"
"any" after "Education:"
"part-time", "2/2 (day/night)" after "Schedule:"
All what I imagine is that
HtmlNode experience = hd.DocumentNode.SelectSingleNode("//td[#class='pl22']//p[#class='bold']");
But it get me different element, which place in the top of the page. My Experience, Education and Schedule is static values. In additional my any, any part-time day/night is the dynamic values. Can anybody help me?
Below is an alternative which is more focused on the table headers (Experience, Education and Schedule), instead of the node classes:
private static List<string> GetValues(HtmlDocument doc, string header) {
return doc.DocumentNode.SelectNodes(string.Format("//p[contains(text(), '{0}')]/following-sibling::p", header)).Select(x => x.InnerText).ToList();
}
You can call that method like this:
var experiences = GetValues(doc, "Experience");
var educations = GetValues(doc, "Education");
var schedules = GetValues(doc, "Schedule");
experiences.ForEach(Console.WriteLine);
educations.ForEach(Console.WriteLine);
schedules.ForEach(Console.WriteLine);
You could do it something like this if you want to keep the XPath
var html = "<td class='pl22'><p class='pb10 pt10 t_grey'>Experience:</p><p class='bold'>any</p></td><td class='pb10 pl20'><p class='t_grey pb10 pt10'>Education:</p><p class='bold'>any</p></td><td class='pb10 pl20'><p class='pb10 pt10 t_grey'>Schedule:</p><p class='bold'>part-time</p><p class='text_12'>2/2 (day/night)</p></td> ";
var doc = new HtmlDocument
{
OptionDefaultStreamEncoding = Encoding.UTF8
};
doc.LoadHtml(html);
var part1 = doc.DocumentNode.SelectSingleNode("//td[#class='pl22']/p[#class='bold']");
var part2 = doc.DocumentNode.SelectNodes("//td[#class='pb10 pl20']/p[#class='bold']");
foreach (var item in part2)
{
Console.WriteLine(item.InnerText);
}
var part3 = doc.DocumentNode.SelectSingleNode("//td[#class='pb10 pl20']/p[#class='text_12']");
Console.WriteLine(part1.InnerText);
Console.WriteLine(part3.InnerText);
Output :
any
part-time
any
2/2 (day/night)

How to Update All Rows of Table SQL

Below is my code:
#{
Layout = "/_SiteLayout.cshtml";
var db = Database.Open("MyDatabase");
var query = "SELECT * FROM Team";
var Teams = db.Query(query);
}
<form>
<table>
<tr>
<td>Team Name</td>
<td>Played</td>
<td>Points</td>
</tr>
#{ foreach(var Team in Teams){
<tr>
<td>#Team.TeamName</td>
<td><input type="text" value="#Team.Played" name="Played"/></td>
<td><input type="text" value="#Team.Points" name="Points"/></td>
</tr>
}
}
</table>
</form>
This is the result:
So what I want to do is update my whole table.
What is the SQL query to do this? I want to update Points and Games Played in my database for all teams once the form is posted.
I don't actually understand what exactly you are trying to achieve (update your whole table with what?), but here is some information you might find useful:
SQL Update Tutorial, SQL Update, Update from Select
Following is My Solution. Anyone have an efficient Solution?
#{
var db = Database.Open("MYDATABSE");
var query = "SELECT * FROM Team";
var Teams = db.Query(query);
var InsertQuery = "";
if(IsPost){
foreach(var Team in Teams){
var Points = Request[Team.TeamName];
var TeamId = Team.TeamId.ToString();
var Played = Request[TeamId];
var executeQueryString="UPDATE Team Set Points=#0, Played=#1 WHERE TeamId=#2";
db.Execute(executeQueryString, Points, Played, Team.TeamId);
}
Response.Redirect("~/UpdateTable.cshtml");
}
}
<br /><br />
<form action="" method="post">
<table>
<tr>
<td><h5>Team Name</h5></td>
<td><h5>Played</h5></td>
<td><h5>Points</h5></td>
</tr>
#{ foreach(var Team in Teams){
<tr>
<td>#Team.TeamName</td>
<td><input type="text" value="#Team.Played" name="#Team.TeamId"/></td>
<td><input type="text" value="#Team.Points" name="#Team.TeamName"/></td>
</tr>
}
}