Way to frame an update query with parameters - javascript

I am working on an application in Appcelerator Titanium. The application uses sqlite database. For inserting into the database, I have written a query with parameters like this:
db.execute("INSERT INTO formData (unique_id,form_xml_id,dateTime_stamp,data,user_id,status) VALUES ('" + Ti.App.mydata._guid + "'," + findex + ",'"+datetime+"','"+fdata1+"'," + Ti.App.information.user_id + ",'" + formstatus + "')");
I have another query to update the database for a different table. But the query is without parameters. Like this:
db.execute("UPDATE formData SET form_xml_id=" + findex + ",dateTime_stamp='" + datetime + "',data='" + fdata + "',user_id=" + Ti.App.information.user_id + ",status='"+ DataStatus +"' where unique_id='" + Ti.App.mydata._guid + "'");
I want to rewrite the update query, like the insert query. How can I do that?

I have a code which update Contacts... you can modify it accordingly:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}

Related

Knex - Result of SUM queries between knex and mysql workbench return different values

I am currently facing this issue when summing fields. I am using Knex and Mysql.
When using Knex, I get this result for the LastYr column..
Knex Result:
But doing the same query in Mysql Workbench, I get this (which is what I want)
Mysql Workbench:
My query is this:
SELECT t1.*, IFNULL(t2.TotalUnits,0) AS TotalUnits, ROUND(IFNULL(t2.totalRevenue,0),0) AS TotalRevenue FROM (SELECT BranchDept, ForPeriod, SUM(SysGen) AS Gen, SUM(UserInput) as Live, SUM(PrevYear) AS LastYr, SUM(SysGen) - SUM(UserInput) AS Input FROM tbl_demand_forecast_details WHERE BranchDept='" + req.body.branchdept + "' AND ForPeriod >= '" + fystart + "' " +
"AND ForPeriod <= '" + fyend + "' GROUP BY BranchDept, ForPeriod " +
"ORDER BY ForPeriod) AS t1 " +
"LEFT OUTER JOIN " +
"(SELECT BranchDept, AsOfPeriod, SUM(UnitSales) AS totalUnits, SUM(PesoSales) AS totalRevenue FROM tbl_sales_history " +
"WHERE BranchDept='" + req.body.branchdept + "' AND AsOfPeriod >= '" + fystart + "' AND AsOfPeriod <= '" + fyend + "' GROUP BY AsOfPeriod) AS t2 " +
"ON t1.BranchDept = t2.BranchDept AND t1.ForPeriod = t2.AsOfPeriod
It seems knex is adding the previous value to the next in the LastYr column.
I tried this with knex.raw and using the knex methods, and I still get the wrong values.
This is driving me nuts for the past two days. Anyone point me to the right direction?
Okay. I finally got it.
The SUM query goes haywire when there are null values on the column being summed. Replacing those with zeroes fixed this issue.

mysql parse error shows when query has 3 conditions

i have a select query to a local database and for some reason the following error shows up:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM site WHERE name = OCC AND date_start = 2018-07-30 08:00:00 AND date_end = '' at line 1
here's my query:
connection.query("SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2, function (err, result)
{
if (err)
{
console.log("Error Is:" + err);
}
else
{
console.log('DATA EXISTING IS =' + JSON.stringify(result));
}
});
am i missing something?
The usual mantra: use parameterized queries. They will prevent SQL injections and make your service more secure. Furthermore they will take care of the usual pitfalls when building a query using string concatenation.
Let's have a look at your query
"SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2
Which spells out to something like
SELECT *, FROM shop WHERE name = myshop AND date_start = 2018-07-30 AND date_end = 2018-08-10
There are at least 3 errors
The , behind the SELECT * this is also the one the error tells you about. I suppose you had a column list and replaced it with *
The shop name column is most certainly some char column. So you have to enclose your values with quotes
Also the dates must be used with quotes, so the SQL engine will parse it to a date and do the comparison. For some SQL engines there is also a special annotation for dates. Have a look in the documentation.
This query should work
"SELECT * FROM shop WHERE name = '" + shop_name + "' AND date_start = '" + myDate + "' AND date_end = '" + myDate2 +"'"
depending on what myDate and myDate2 are.
At least problems 2 and 3 would not happen if you use parameterized queries. Consult the documentation of the library you are using.

adding to a value in a database not replacing it

So i am storing my users 'freinds' in a database and i am currently using this to add there freind to it
socket.on('addFreind', function(username, freind) {
console.log("ADD FREIND " + freind + "TO " + username)
let query = 'update users set freinds="' + freind + '" where username = "' + username + '"';
connection.query(query, function(err) {
console.log(err)
});
});
but that just replaces the original value with the new one how can i add to the original value
i have tried querying the original value and adding it to an array and then adding the new value to that array then putting it in my database but that failed horribly and i was wondering if there was just a simple way to do this

Javascript variable, different values, same line

First of all, let me apologize for the title, as it isn't so explanatory, but I could not say it in another way.
The deal is: I am doing a javascript application, in which I have an object called "ocorrencia", which was defined like this:
var ocorrencia = new Object();
that object has several children, being filled by a method:
ocorrencia.idOcorrencia = ""+ year + month + day + hour + minute + second + milisec;
idOcorrencia is the one I am having problems with, because I am running a DataBase insert with this value, and I use it 2 times in the same insert, like:
var sql = 'INSERT INTO OCORRENCIAS (id, ocorrencia, data, resolucao, urgencia, foto) VALUES (' + ocorrencia.idOcorrencia + ', "' + ocorrencia.descricao + '", "' + ocorrencia.data + '", "' + ocorrencia.resolucao + '", "' + ocorrencia.grauUrg + '", "' + ocorrencia.idOcorrencia + '.jpg"' +')';
The insert runs great, an I have all the data inserted in the DB, BUT "id" and "foto" (which were supposed to get equal values) are giving me different values by 2 or 3 miliseconds.
How can this happen, as I am not changing "ocorrencia.idOcorrencia" ?
This is beeing tested in an Android device.
EDIT: Tested on Windows browser and the problem doesn't appear to happen.
Thank you
I guess you fill idOcorrencia on runtime? So the lag is producing this difference.
Try using a hash for the id or set it before running the SQL-query.

Save XML To Database using Javascript

I'm trying to save content to an XML data type to Microsoft SQL Server,
using Javascript code.
var sql = "INSERT INTO Screen_Template(template_xml, template_name, OpCo, env, language, id, title, role, UID) VALUES (N'" + XMLText + "',N'" + templateName + "',N'" + opco + "',N'" + env + "'" + ",N'eng'," + maxID + ",N'Hermes SMS message composer'," + "N'manag', N'10')";
connection.execute(sql);
But, I'm getting an error, what can be the problem?

Categories

Resources