Connect to a local db from testcomplete - javascript

I am trying make a query from test complete to an Oracle db.
This is what I have so far:
function main (){
var result = query("select * from appsettings where settingid = 10")
function query (sqlQuery) {
var dbObj = ADO.CreateADOQuery();
dbObj.ConnectionString = "Provider=OraOLEDB.Oracle;Data Source='localhost:1521/ORCL';User Id='someUser';Password='somePass';OLEDB.NET=True;";
dbObj.SQL = sqlQuery;
dbObj.Open();
queryResult = dbObj;
return queryResult;
}
Log.Message("Query result is: " + result)
}
The problem is that result has no value.. and the message I get is:
Query result is:

The query object cannot be printed itself. You need to get data from the object. For example:
...
sqlQuery.First();
while (!sqlQuery.EOF) {
Log.Message(sqlQuery.FieldByName("FirstName").Value + " " + sqlQuery.FieldByName("LastName").Value);
sqlQuery.Next();
};
sqlQuery.Close();

Related

JavaScript MySql INSERT statement for multiple rows through URL

Good day !
I am trying to send an object array to my MySql Database through an url using an API.
Here is the code on my API :
app.get("/orderdetails/add", (req, res) => {
const {
item__,
Qty_Ordered,
Unit_Price,
Ext_Price
} = req.query;
const INSERT_ORDERDETAILS_QUERY = `INSERT INTO oe_details (item__,
Qty_Ordered, Unit_Price, Ext_Price) VALUES('${item__}', '${Qty_Ordered}',
'${Unit_Price}', '${Ext_Price}')`;
connection1.query(INSERT_ORDERDETAILS_QUERY, (err, results) => {
if (err) {
return res.send(err);
} else {
return res.send("successfully added order details");
}
});
});
And below is the function on my App :
addOrderDetails = _ => {
const o = this.props.o;
const summary = o.filter(function(obj) {
return obj.Quantity >= 1;
});
var url = "";
summary.forEach(function(e) {
url +=
"item__=" +
e.ExternalID +
"&Qty_Ordered=" +
e.Quantity +
"&Unit_Price=" +
e.Price +
"&Ext_Price=" +
e.ExtPrice +
"&";
});
url = url.trim("&");
fetch(`http://localhost:4000/orderdetails/add?${url}`).catch(err =>
console.error(err)
);
};
When I run addOrderDetails, I end up sending the following statement to MySql:
INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price)
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75')
Which is wrong... is there a way for me to add multiple rows to mysql database using the same concept ?
it works fine if I only have 1 row to add...
Help would be greatly appreciated !
Thanks,
To insert multiple rows, MySQL statement should be like
INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price)
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75'),
VALUES('C-2080,C-2081', '8,5', '18.75,18.75', '150,93.75'),
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75');
You can change your API to a POST call and send an array of your data to it, and within your API you can form the above query.
You can use a simple for loop to create such query.
let summary = [1,2,3,4] // dummy data
let INSERT_ORDERDETAILS_QUERY = `INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price) VALUES`
summary.forEach(function(data, i) {
INSERT_ORDERDETAILS_QUERY = `${INSERT_ORDERDETAILS_QUERY} (${data})`;
INSERT_ORDERDETAILS_QUERY = (i !== summary.length - 1) ? `${INSERT_ORDERDETAILS_QUERY}, ` : `${INSERT_ORDERDETAILS_QUERY};`;
})
Hope this helps!

Node.js giving empty array for dependent queries

I have PHP website in which, chat module is working fine ( via ajax ).
Now I am creating Ionic app for this chat module, So I am trying to convert my PHP code on NODE.js
To get a list of chat users i wrote this code in helper.js file
setMessage:function(message1){
message=message1;
},
setPeople:function(id,people1){
people[id]=people1;
},
setChatlist:function(data9){
chatlist.push(data9);
},
setRecorder:function(data8){
recorder.push(data8);
},
getUserChatList:function(uid,connection,callback){
chatlist=[];
recorder=[];
people=[];
message={};
var data={
query:"select id from messages where recipient_id='"+uid+"' or timeline_id='"+uid+"' order by timestamp desc ",
connection:connection
}
var db_conncetion=data.connection;
var query=data.query;
var insert_data=data.insert_data;
db_conncetion.getConnection(function(err,con){
if(err){
con.release();
}else{
con.query(String(query),insert_data,function(err,rows){
if(!err) {
if(rows.length>0){
query1="select DISTINCT recipient_id from messages where timeline_id='"+uid+"' order by timestamp desc ";
con.query(String(query1),insert_data,function(err1,rows1){
rows1.forEach(function(element1, index1, array1){
var receiverId=element1.recipient_id;
var receiverSql = "SELECT time,text FROM messages WHERE timeline_id=" +uid+ " AND recipient_id=" +receiverId+" ORDER BY time DESC";
con.query(String(receiverSql),insert_data,function(err2,rows2){
rows2.forEach(function(element2, index2, array2){
people[receiverId]=element2.time;
message[receiverId]=element2.text;
});
self.setMessage(message);
self.setPeople(people,people);
});
});
});
var senderIdSql = "SELECT DISTINCT timeline_id FROM messages WHERE recipient_id=" +uid+ " ORDER BY time DESC";
con.query(String(senderIdSql),insert_data,function(err3,rows3){
rows3.forEach(function(element1, index1, array1){
var senderId=element1.timeline_id;
var senderSql = "SELECT time,text FROM messages WHERE recipient_id=" +uid+ " AND timeline_id=" +senderId+ " ORDER BY time DESC";
con.query(String(senderSql),insert_data,function(err2,rows2){
rows2.forEach(function(element2, index2, array2){
if (!self.isset(people[senderId]) || element2.time > people[senderId])
people[senderId]=element2.time;
message[senderId]=element2.text;
self.setPeople(senderId,element2.time);
self.setMessage(message);
});
});
});
});
}
Object.keys(people).forEach(function (key){
var tempArray={};
tempArray['id']=key;
tempArray['text']=message[key];
self.setRecorder(tempArray);
});
recorder.forEach(function (key){
var user_query="SELECT * FROM accounts WHERE id=" +key +" AND active=1 ";
con.query(String(user_query),insert_data,function(err3,rows3){
var tmp1=[];
rows3.forEach(function(element2, index2, array2){
var data1={};
data1['receiver_id']=element2.id;
data1['receiver_username']=element2.username;
data1['receiver_name']=element2.name;
data1['receiver_thumbnail_url']=element2.thumbnail_url;
data1['receiver_online']=0;
data1['receiver_message'] = recorder[key];
tmp1.push(data1);
});
self.setChatlist(tmp1);
});
});
var ret_data={};
ret_data['status']=200;
ret_data['success']=1;
ret_data['messages']=chatlist;
console.log(ret_data);
console.log("1111");
callback(ret_data);
con.release();
//console.log(message);
} else {
console.log(err);
console.log("Query failed");
}
});
}
});
}
But when i am calling this method via socket it's giving an empty array
listening in http://localhost:3000
{ status: 200, success: 1, messages: [] }
1111
Please tell why it's giving an empty array?
It is supposed to be an empty array according to your current code.
All the db calls will be asynchronous and will not wait for its completion. It will execute the next line which will execute the following code before the db calls get finished:
var ret_data = {};
ret_data['status'] = 200;
ret_data['success'] = 1;
ret_data['messages'] = chatlist;
console.log(ret_data);
console.log("1111");
callback(ret_data);
con.release();
//console.log(message);
So your callback gets executed with initial value that is [] and thus you have the value as [].
You have to manage the db calls and the data to be sent. You can use promises or async/await to this. The code will be much more clean and traceable. Take a good look at them.

I am trying to write a trigger in parse.com but some error

Parse.Cloud.afterSave("StatusTable", function(request) {
var deviceName = request.object.get("deviceName");
var lastSeen = request.object.get("entryTime");
var sectionName = request.object.get("sectionName");
var LastSeen = Parse.Object.extend("LastSeen");
var query = new Parse.Query(LastSeen);
query.equalTo("deviceName", deviceName);
query.first().then(function(result) {
result.put("lastSeen", lastSeen);
result.put("sectionName", sectionName);
result.save();
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
);
I have two tables in parse. StatusTable and LastSeen table.I need to write a trigger which updates lastSeen and sectionName columns of LastSeen table when a successful insert has occurred in StatusTable corresponding to the deviceName.This code is not working.
StatusTable
LastSeenTable
From the Object documentation: https://parse.com/docs/js/api/classes/Parse.Object.html
There is no put() method. Try using set() instead:
query.first().then(function(result) {
result.set("lastSeen", lastSeen);
result.set("sectionName", sectionName);
result.save();
});
Also, are you sure you want your query to use first instead of find? Just to ensure that you are always updating the object that you want.

How to query an array value from scriptDB?

I'm trying to access a global variable from a main function to a handler function using scriptDb.
Following the [documentation instructions][1], I create a piece of code similar to this:
function showList(arrayList) {
Logger.log("arrayList argument value = " + arrayList);
var arrayToUse = {
arrayName: 'theses',
arrayValue: arrayList,
};
var record = db.save(arrayToUse);
var scriptDbObject = db.query({arrayName: 'theses'});
var arrayList = scriptDbObject.arrayValue;
Logger.log("ShowList arrayList query value = " + arrayList);
}
But when I try to query the inserted item, It doesn't work:
![enter image description here][2]
The argument arrayList is OK (as the log shows).
I also tried this other code, following as similar as I could [this stackoverflow question][3]:
function showList(arrayList) {
Logger.log("arrayList argument value = " + arrayList);
var record = db.save({arrayName: "savedArray", arrayValue: arrayList});
var result = db.query({arrayName: 'thesesRequests'});
if (result.hasNext()) {
arrayList = result.next().data;
}
else {
arrayList ["empty array", "empty", "array"];
}
Logger.log("ShowList arrayList query value = " + arrayList);
And I got the same undefined message.
What is going wrong here?
[1]: https://developers.google.com/apps-script/guides/script-db/
[2]: http://i.stack.imgur.com/5CpyY.png
[3]: Error when trying to store an array in ScriptDb
That first go of yours was on the mark, except that when u do a query you need to use the next() operator on the result to get the actual dbResult entry:
function showList(arrayList) {
Logger.log("arrayList argument value = " + arrayList);
var arrayToUse = {
arrayName: 'theses',
arrayValue: arrayList,
};
var record = db.save(arrayToUse);
var scriptDbObject = db.query({arrayName: 'theses'});
if (scriptDbObject.hasNext()) {
var dbItem = scriptDbObject.next();
var dbArrayList = dbItem.arrayValue
Logger.log("ShowList arrayList query value = " + dbArrayList);
}
}

SQL Insert Statement not Working in Javascript

I'm trying to get my WebSQL database to popluate using a JSON array (Object is called myJSONObject, array is called costcodes).
The function runs on click, the database successfully creates, but the data is not inserted into the database. It doesn't even throw and error, it just doesn't do anything.
My initial thought was that the data isn't escaped properly, but I don't know exactly where/how to escape it. So I'm stumped.
localDB = null;
function initDB()
{
if (localDB==null)
{
var shortName = 'Costcode';
var version = '1.0';
var displayName = 'Costcode';
var maxSize = 217802; // in bytes
localDB = window.openDatabase(shortName, version, displayName, maxSize);
}
}
function buildTable()
{
var sQuery = 'CREATE TABLE IF NOT EXISTS Costcode ('+
'id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,' +
'cost_code_no VARCHAR NULL,' +
'row_unique_no VARCHAR NULL,' +
'cost_class_no VARCHAR NULL,' +
'Table_Version VARCHAR DEFAULT "1.0");';
try
{
initDB();
localDB.transaction(function(transaction)
{
transaction.executeSql(sQuery, []);
console.log('sucess');
});
}
catch (e)
{
alert("Error: Unable to create table 'x" + "' " + e + ".");
return;
}
}
function exeSQLFast()
{
initDB();
localDB.transaction(function(transaction)
{
for (var x = 0; x <myJSONObject.costcodes.length; x++)
{
var costcodeno = myJSONObject.costcodes[x].cost_code_no;
var rowuniqueid = myJSONObject.costcodes[x].row_unique_id;
var costclassno = myJSONObject.costcodes[x].cost_class_no;
console.log(costcodeno);
console.log(rowuniqueid);
console.log(costclassno);
transaction.executeSql('INSERT INTO Costcode (cost_code_no, row_unique_id, cost_class_no) VALUES (? , ? , ?)',
[costcodeno,
rowuniqueid,
costclassno]
, function(transaction, results)
{
console.log(costcodeno);
console.log('hooray');
}
)};
}
)}
</script>
</head>
<body onLoad="buildTable();">
<input type="button" onClick="exeSQLFast();" value='button'>
</body>
</html>
The console log shows that the variables are all being properly defined, but it's not running the insert statement. Any ideas?
Here's an example of myJSONObject.costcodes[2]
cost_class_no: " 3"
cost_code_no: " 1000"
row_unique_id: 335
That looks like a problem doesn't it...
The problem was that I called the row_unique_no column row_unique_id in the insert statement. Now I feel stupid.
But if anyone is curious how to populate a WebSQL database properly, this is how you do it. Just don't mistype the column names.

Categories

Resources