How to get output from NodeRed Mysql node - mysql

I want to get out put from NodeRed mysql node.
Here image of connection :
Select Query is :
msg.topic = "SELECT * t.TableID FROM booking t where t.bookingdate='"+formattedDate+"' and t.TableID = 3";
Output i am trying to get:
if(msg.payload.TableID ==3){
var id = "15";
var message = "Front Desk";
msg.topic = "INSERT INTO tableMessage(TableID, MESSAGE) VALUES ('"+id+"' ,'"+message+"')";
return msg;
}
Question is msg.payload.TableID ==3 is it right? is it right way to read out put from Mysql node
Select query are tested working fine.
but this condition not working for me.
any one help me how to retrieve data from mysql node.
Thanks

The output from the mysql node is an array of rows so your test should be something like this:
if (msg.payload[0].TableID ==3) {
...
EDIT:
You can test if no results were returned by testing the content of msg.payload
if (!msg.payload) {
//no results
} else if (msg.payload[0].TableID == 3) {
//results
}

Related

Unable to retrieve data from my sql database using pymysql

I have been trying to retrieve data from my database. I was successful, however, this time inside an if statement. The code looks like:
cur_msql = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
select_query = """select x,y,z from table where type='sample' and code=%s"""
cur_msql.execute(select_query, code)
result2 = cur_msql.fetchone()
if(result2==None):
insert_func(code)
select_query = f"""select x,y,z from table where type='sample' and code='{code}'"""
mycur = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
print(select_query)
mycur.execute(select_query)
result3 = mycur.fetchone()
if(result2==None):
result2=result3
Now I see that insert_func does successfully insert into the 'table'. However, on trying to fetch that row, immediately after the insertion, it returns None as if the row is absent. On debugging I find that result3 is also None. Nothing looks wrong to me but it's not working.
you donĀ“t execute it in the right way, in the cur_msql.execute, you the to send the query and a tuple of values, and you are sending just a value:
cur_msql = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
select_query = "select learnpath_code,learnpath_id,learnpath_name from contentgrail.knowledge_vectors_test where Type='chapters' and code=%s"
cur_msql.execute(select_query, (meta['chapter_code'],))
result2 = cur_msql.fetchone()

Mule ESB, issue when adding up numbers within a JSON array

I use the following dynamic query (even though I could have used a prepared stmt) in my Database COnnection node:
SELECT BALANCE FROM xxx.TAB
I have the following expression in the SetPayload command that is run immediately after the Datbase Connection node:
#[message.payload]
and I get the following response from curl:
[{"BALANCE":111.11},{"BALANCE":222.12},{"BALANCE":444.30}]
So I modify the flow, putting an expression node between the Database connection node and the SetPayload node with the following expressions:
sum = 0;
foreach (row : message.payload) {
sum += row['BALANCE'];
}
message.payload = sum;
I run curl again, but this time I get the following:
777.5299999999999994315658113919199
Actually, the answer should be 777.53
What happened to this data?
Is there a way to fix this ?
Thanks
It's because the value is a Float or Double. Take a look at something like: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Bit messy, but something like:
sum = 0;
foreach (row : message.payload) {
sum += row['BALANCE'];
}
message.payload = new java.text.DecimalFormat("#.##").format(sum);

nodejs and sql queries - concurrent access

I'm discovering nodejs and its asynchronous system and I'm doing a query in MySQL with the node-mysql package. I'm doing something like that:
iterating a collection
if the item is not in the DB, I insert
if the item is in the DB, I update
So my code look like that:
var stuff = ['a', 'b', 'a'];
for(var i=0;i<stuff.length;i++){
connection.query("SELECT COUNT(*) AS count FROM table WHERE column = ?", [stuff[i]],
(function(err, rows){
if(rows.count == 0){
connection.query("INSERT INTO table ...");
} else {
connection.query("UPDATE table SET ...");
}
}).bind(this)
}
But I'm wondering, because of asynchronous mode, if sometimes there is a problem with this pattern. What is the behavior here ?
"SELECT WHERE column = 'a'" ==> count == 0
"SELECT WHERE column = 'b'" ==> count == 0
"SELECT WHERE column = 'a'" ==> count == 0
"INSERT 'a'"
"INSERT 'b'"
"INSERT 'a'" ==> unexpected behavior
or
"SELECT WHERE column = 'a'" ==> count == 0
"INSERT 'a'"
"SELECT WHERE column = 'b'" ==> count == 0
"INSERT 'b'"
"SELECT WHERE column = 'a'" ==> count == 1
"UPDATE 'a'" ==> expected behavior !!
I hope you will understand my problem, sorry for my bad english, it's a real handicap..
Thank you.
mysql has a insert or update command, http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html This will insert if it doesn't exist, or update if it does.
As for insert/update with this async behavior, take a look at the async lib to run things like this in series instead. With your code example above, you can't be sure which will run/finish first IIRC.
It also depends on what exactly you are trying to update. If you are just going to count something, and need to increment the count, order doesn't matter. Again, this all depends on what you actually want to insert/update.
I find that recursion often works great for this kind of challenge. I use it all the time - it seems simpler than resorting to async for such a straight-forward problem.
Something like this:
var stuff = ['a', 'b', 'a'];
processStuff(stuff);
function processStuff(theStuff) {
if (theStuff.length) == 0 {
// Done all items - either return result to client or execute some callback here
// res.end('Completed');
return;
}
var thisItem = theStuff.shift();
connection.query('SELECT * FROM table WHERE column = ' + connection.escape(thisItem), function(err, rows) {
if (rows.length == 0) {
connection.query("INSERT INTO table ...", function(err, result) {
processStuff(theStuff);
});
} else {
connection.query("UPDATE table SET ...", function(err, result) {
processStuff(theStuff);
});
}
});
}
This will keep your queries and updates/inserts flowing one after another, and yet it is still asynchronous. I find this easier to read as well, and easy to modify.

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

How do I use Count and Group in a select query in Linq?

I had the following Linq code:
var allRequests = model.GetAllRequests();
var unsatisifedRequests = (from request in allRequests
where request.Satisfied == false
select request)
.OrderBy(r => r.RequestedOn)
.GroupBy(r => r.RequestedCountryId);
After which I then did a foreach over unsatifiedRequests building a new TOARequestListSummary object for each. This meant if I "returned" 4 items from the query, it would make 4 calls to the DB, once per loop of the foreach to grab the individual rows.
This seems to be the wrong way to use Linq, so I tries to convert this query to one which used projections to return the TOARequestListSummary objects directly and I came up with:
var summaries = (from request in allRequests
where request.Satisfied == false
group request by request.RequestedCountryId into requestGroups
select new TOARequestListSummary
{
CountryName = requestGroups.First().RequestedCountry.Description,
RequestCount = requestGroups.Count(),
FirstRequested = requestGroups.First().RequestedOn
});
But when I run this, I get the following exception:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
I have got as far as knowing that the Linq equivalent to EXISTS is Contains, but I have no idea how to indroduce this into the query.
This should work for you:
var summaries = (from request in allRequests
where request.Satisfied == false
group request by request.RequestedCountry into g
select new TOARequestListSummary
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.Min(i => i.RequestedOn)
});
In your original version of this query (the second one you posted), your group's key was the RequestedCountryId. Though this will technically be grouping on that, you actually want to use the associated object. This way you'll have easy access to the needed properties and won't need to worry about grabbing the first item.
Sorry, this is an answer, rather than an additional comment to Ryan's answer, but it is too long to fit...
This gets very strange. In LinqPad the following works a treat:
from request in TOARequests
where request.Satisfied == false
&& request.Active == true
orderby request.RequestedOn
group request by request.RequestedCountry into g
select new
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.First().RequestedOn
}
But the following throws the same translation exception in C#
var summaries = (from request in context.Repository<TOARequest>()
where request.Satisfied == false
&& request.Active == true
orderby request.RequestedOn
group request by request.RequestedCountry into g
select new
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.First().RequestedOn
}).ToList();
The only difference I can see if the ToList(), but even without that when I try to enumerate the list, it throws the exception.