Get value from Titanium Appcelerator db column - sql

I've looked around everywhere, but I can't seem to find exactly what I'm trying to do. It should be fairly simple...
I have a db table set up like this:
var db = Ti.Database.open('playerInfo.db');
db.execute('CREATE TABLE IF NOT EXISTS playersTable (id INTEGER PRIMARY KEY, name TEXT NOT NULL, "50" INTEGER, "25" INTEGER )');
I have two buttons with an assigned value of 25, and 50, respectively. Each button has a "value" key, where I assign their values. I am trying to accomplish three things:
When a button is pressed, find the column of corresponding value.
increase the value of this column by 1.
Retrieve the new value and console log it.
This is what my code looks like when a button is pressed:
var rows = db.execute("SELECT '" + button.value + "' FROM playersTable WHERE name= '" + owner + "'");
var imagesString = rows.fieldByName(button.value);
Ti.API.debug(imagesString)
This is all in a click event listener where the variable "owner" is passed in as a string.
This is the error I get:
message = "Attempted to access unknown result column 25";
I don't have too much experience with sql, so I'm not sure what I'm doing right and what I'm doing wrong. Any help is appreciated!
Thanks.

I'm not sure quite exactly what the problem is, but the following works for me. Note that the "?" variable substitution syntax makes sure that the values are quoted properly for MySQL:
button = e.source;
db = Titanium.Database.open('test');
var rows = db.execute("SELECT * FROM playersTable WHERE name= ?", "foo");
// Theoretically this should be returning a single row. For other results,
// we would loop through the result set using result.next, but here just check if
// we got a valid row.
if (rows.isValidRow()) {
var imagesString = rows.fieldByName(button.value);
var id = rows.fieldByName('id');
imagesString = imagesString + 1;
Ti.API.info("id = " + id + " val = " + imagesString);
// The ? substitution syntax doesn't work for column names, so we
// still need to stick the button value into the query string.
db.execute('UPDATE playersTable set "' + button.value +'"= ? where id = ?', imagesString, id);
}
else
{
Ti.API.info("Row not found.");
}
db.close();
If you get the row not found error, it's possible your data isn't getting inserted properly in the first place. Here's how I inserted my test row for player "foo":
db.execute('insert into playersTable (name, "50", "25") values (?,?,?)', 'foo', 0, 0);
I think this should solve your problem. Let me know if this doesn't work for you.

Related

Checking if GroovyRowResult field is empty string

I am using sql.firstRow to check if a row exists in the postgres database based on some criteria.
def cur = sql.firstRow(r, '''
SELECT "some_thing"
FROM "my_table"
WHERE "customer_name" = :customer_name
AND "sad_date" = :sad_date
AND "forgiver" = :forgiver
''')
I find that this works:
if (cur){
log.debug("Found Some thing " + cur["some_thing"])
log.debug("Cur: " + cur.keySet())
}
however this lets in any rows that don't have some_field inside it.
ISSUE
To avoid this, when we try and check for the existance of a non empty value for some_field on the result row like this:
if (cur && "${cur.some_thing}" ){
log.debug("Found Some thing " + cur["some_thing"])
}
ERROR
I get an error suggesting that:
No signature of `String.positive` for argument types for the given type.
I have read this question and changed from cur.some_thing and cur['some_thing'] to "${cur.some_thing}" but the error does not go away
I have also tried this post and tried to use cur.getProperty("some_thing") and it still throws the same error.

SQL String or binary data would be truncated

I'm trying to search the max ID in the database, then increment it by 1 for each new entry as shown below:
var query2 = dbb.Database.SqlQuery<patient_visit>("SELECT MAX(CAST(SUBSTRING(pvid, 3, 10) AS int)) FROM patient_visit");
if (query2 != null)
{
objDetails.pvid = query2.ToString();
objDetails.pvid += 1;
objDetails.pvid = "PV" + objDetails.pvid;
}
string sql = "INSERT INTO patient_visit (pvid,paid) " +
"VALUES('" + objDetails.pvid + "', '" + paid + "')";
But when i try to insert it in the database, it gives out error
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: String or binary data would be truncated.
I've tried running the query in SQL Server and checked the value of 'pvid', it is 10 so after i include 'PV' to the integer pvid, it should be 12. So it should be fine, but why did i get that error? Please can anyone help me?
[Key]
[MaxLength(20), MinLength(12)]
public string pvid { get; set; }
When i replace the pvid with hard code ID, it works just fine. Why is this happening?
P/S: I know its not advisable to simply concatenate the input data with the query, but i've also tried querying using parameterized query but it gives same error.
string sql = "INSERT INTO patient_visit (pvid,paid) " +
"VALUES(#pvid, #paid)";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("#pvid", objDetails.pvid));
parameterList.Add(new SqlParameter("#paid", paid));
SqlParameter[] parameters = parameterList.ToArray();
dbb.Database.ExecuteSqlCommand(sql, parameters);
Check the Field length of the column you are trying to put the data into.
I have had this problem before where the column was varchar(10) and I was trying to concatenate two char strings of 6 characters each. Making them 12 characters long. 2 longer than the target field.
Your problem might be similar.

Getting all the cell values from table using table header using Webdriver

Below is the HTML code for the tables:
I need to extract values from table preceding with header as "Opportunities".
Could someone please suggest the best way forward as I can extract values fine if they belong to the same table but I need help when they are in two different table and i need to look for table opportunities and than extract data from the preceding table.
Sure here is my best interpretation of what you need in Java. Any questions and I'll alter my solution to accommodate them. This starts with an index of 0,0 for row and column.
int row = 0, column = 1; //it's 1 to accommodate fogr the first thing you want being a 'th' tag
List<WebElement> tableRows = driver.findElements(By.className("dataRow"));//this gets all elements on your page with a class of dataRow (which are your tr's)
for(WebElement singleRow: tableRows) //this for loop increments each of these tr's
{
System.out.println(singleRow.findElement(By.xpath("th[1]/a[1]")).getText()); //I'll have to use an xpath here because I don't have time to play around with other solutions but it'll work
System.out.println("Row: " + row + ", Column: " + column);
List<WebElement> rowTDs = singleRow.findElements(By.tagName("td"));//this gets every td in the current tr and puts it into a list
for(WebElement singleTD: rowTDs) //this increments through that list of td's
{
System.out.println(singleTD.getText()); //this gives you back the text contained in that cell
System.out.println("Row: " + row + ", Column: " + column);
column++; //increment the column counter
}
column=1; //reset the column
row++; //increment the row counter
}
Edit: It seems that given that element of the request "Saykiro" has almost the right of it and you can replace in my solution tableRows = with this, there's probably a more succinct way to get the second table but this is what comes to me:
WebElement table1 = driver.findElemen(By.id("001Z000000vrLQe_RelatedOpportunityList_title"));
WebElement table2 = table1.findElement(By.xpath("../../../../following-sibling::table"))
List<WebElement> tableRows = table2.findElements(By.className("dataRow"));
For your case:
//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[#class=' dataCell ']
For C# (getting list of values in cells):
var values = driver.FindElements(By.XPath("//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[#class=' dataCell ']")).Select(a=>a.Text);
You should describe outer part of html, so we can build xpath better.

DataContext.ExecuteQuery<object> returns object {}

I'm trying to write function for selecting optional columns in linq(columns that may not exist). The problem is in linq like this:
using (DataDataContext db = new DataDataContext()){
var collection = from t in table
select new
{
Nonoptional = t.A;
Optional = IsInDB("table","B") ? t.B : -1; //this is optional column
}}
Unfortunately, this won't work because the fragment near Optional will be translated to case statement and error arises that column not exists.
So i decided to "cover" it with function:
using (DataDataContext db = new DataDataContext()){
var collection = from t in table
select new
{
Nonoptional = t.A;
Optional = IsInDB("table","B") ? OptionalColumnValue<int>("table","B","id_table",t.id_table) : -1; //this is optional column
}}
I want this function to be universal. It should work like that" If there is no value or column is nullable and value is null then return default value for type.
I came up with something like this:
//table,column - obvious,id_column - PK column of table, id - id of currently processing record
public static T OptionalColumnValue<T>(string table,string column,string id_columm,int id) T t = default(T);
DataDataContext db = new DataDataContext();
IEnumerable<object> value = db.ExecuteQuery<object>("select " + column + " from " + table + " where " + id_columm + " = " + id.ToString());
List<object> valueList = value.ToList();
if (valueList.Count == 1)//here is the problem
t = (T)valueList.First();
return t;
}
When there is null value db.ExecuteQuery return something like object{}. I'm assuming this is "empty" object,with nothing really in there. I was thinking about checking for "emptiness" of this object( BTW this is not DBull).
When i realised that this is no way either with concrete value in this column(it cannot cast it to return correct type), then I tried db.ExecuteQuery<T>. Then concrete value - OK, null - Exception.
I thought, maybe Nullable<T> as return value. Nop, because string also can be T.
I don't know what to do next. Maybe there's another solution to this problem.

Attributes of tables in VS by coding with C#

I have this table:
Please, don't mind because it's on my native language and it doesn't matter..
Those are all attributes in table but when I go to Visual StudioS and try to use some of this I get this one:
I see all "normal" attributes in VS but where is those FK attributes?
I need them to compare few ones and get values?
I can't use it from name of other tables [dot] attribute etc...
like for example:
I need this: table1.ID == table2.ID
and not this: table1.ID == table1.table2.ID
Where or what is FK attribute in VS that is shown in SQL table ??
public void setParametri(int desID)
{
foreach (desavanje d in DM_Class.dc.desavanje)
if (d.desavanjeID == desID)
{
//THIS FIRST 4 LINES WORKS PERFECTLY
this.naziv_des = d.naziv_des;
this.datum_po = d.datum_pocetka.ToString();
this.datum_zav = d.datum_kraja.ToString();
this.cijena = d.cijena_des;
//foreach (klijenti k in DM_Class.dc.klijenti)
//{
// if(k.klijentID == //WHAT TO PUT HERE TO COMPARE VALUE klijentID from tables klijenti with FK value in table desavanje)
// this.klijent = k.Ime + ' ' + k.Prezime;
//}
//ON THIS LINE I'M GETTING ERROR - Object reference not set to an instance of an object. but why?
//I have data on that field in DB ?
//this.grad = d.mjesto_desavanja.gradovi.naziv_grada.ToString();
//this.mjesto = d.mjesto_desavanja.naziv_objekta;
//this.organizator = d.organizator.Ime + ' ' + d.organizator.Prezime;
//this.tip = d.tip_desavanja.vrsta_des;
this.klijent = d.klijenti.Ime + ' ' + d.klijenti.Prezime;
//this.status = d.status_desavanja.naziv_statusa;
//this.br_gost = d.specifikacija_desavanja.br_osoba;
}
}
If is there other solution to get values for attributes I'm willing to try it without using another foreach loop?
Ok, I managed this.. I've used a linq query to generate data that I need and in that queries I've compared needed ID's and finally get some working stuff.