res->getString() crashes the application - mysql

HOW IT SHOULD WORK: User clicks on a listbox with multitude of IDs. Then, the edit controls are filed with the data from the specified ID (row).
HOW IT WORKS: It crashes at res->getString
case LBN_SELCHANGE:
{
string str;
int index = SendMessage(GetDlgItem(hwnd, IDC_lbList), LB_GETCURSEL, 0, 0);
string sint = boost::lexical_cast<std::string>(index);
string smt="SELECT client, telnr, atnrem, papatn, gedapr
FROM tremreg WHERE id = ";
string query = smt + sint;
res = stmt->executeQuery(query.c_str());
//starts crashing here
str = res->getString("client");
SetDlgItemText(hwnd, IDC_eClient, str.c_str());
str = res->getString("telnr");
SetDlgItemText(hwnd, IDC_eTelNr, str.c_str());
str = res->getString("antrem");
SetDlgItemText(hwnd, IDC_eRemAtn, str.c_str());
str = res->getString("paprem");
SetDlgItemText(hwnd, IDC_ePapAtn, str.c_str());
str = res->getString("gedapr");
SetDlgItemText(hwnd, IDC_eGedApr, str.c_str());
delete res;
delete stmt;
}
break;
CRASH INFO:
Unhandled exception at 0x753C812F in Registracija.exe:
Microsoft C++ exception:sql::InvalidArgumentException at memory location 0x0018F7AC.
Digging around google I found somebody mentioning that VARCHAR type values should be fetched with getBlob. That did not help at all though, and crashed just the same. getInt works however, and is used in other parts of the program.
QUESTION: What steps should I take to make it work?

does the same query run properly if you do it in the database directly? Also, are all the returned fields really Strings? And is it valid to call them by name, rather than by the sequence number? I.e. getString(1), etc.

Related

Can I use a value stored in a table as a key in another table?

I'm new to LUA and I still haven't gotten the hang of how classes work in LUA, so my question
probably has a very simple answer. I'm trying to make a function that takes a CSV file and turns it into a lua table.
The input file would be something like this
PropertyKey1,Propertykey2,Propertykey3
object1property1,object1property2,object1property3
object2property1,object2property2,object2property3
object3property1,object3property2,object3property3
and I want the resulting lua table to look something like this
objects = {
{
PropertyKey1 = object1property1
PropertyKey2 = object1property2
PropertyKey3 = object1property3
}
{
PropertyKey1 = object2property1
PropertyKey2 = object2property2
PropertyKey3 = object2property3
}
{
PropertyKey1 = object3property1
PropertyKey2 = object3property2
PropertyKey3 = object3property3
}
}
this is what I have thus far
function loadcsv(path)
local OutTable = {}
local file = io.open(path, "r")
local linecount = 0
for line in file:lines() do
local data = {}
local headers = {}
local headerkey = 1
if linecount < 1 then
for val in line:gmatch("([^,]+),?") do
table.insert(headers, val)
end
else
for word in line:gmatch("([^,]+),?") do
key = headers[headerkey]
data[headerkey] = word
headerkey = headerkey + 1
table.insert(OutTable, data)
end
end
linecount = linecount + 1
end
file:close()
return OutTable
end
The above code does not run. When I try to print any of the values, they come as nil.
The problem is this bit
key = headers[headerkey]
data[headerkey] = word
I wanted to use the values I stored in one table as keys on the second table, but it looks like since LUA only passes the references, that doesn't work.
I did a quick experiment to confirm it. I first set up 2 tables.
test = {}
test2 = {}
test[1]={"index"}
key = test[1]
key2 = "index"
First I tried assigning the value directly form the table
test2[test[1]] = "text"
print(test2.index) --This did not work
then I tried going trough another variable
test2[key] = "texto"
print(test2.index) --This did not work
I even tried using tostring()
key = tostring(test[1])
test2[key] = "texto"
print(test2.index) --This did not work
I wrote the string directly in the variable "key2" to confirm that I was using the right notation.
test2[key2] = "text"
print(test2.index) --This one worked
I read a bit on metatables, but I'm not fully clear on those. Would that be the simplest way to do what I'm trying to do, or is my approach flawed in some other way?
key = headers[headerkey]
key is not used so why assign a value to it?
data[headerkey] = word
headerkey is a numeric key. You start at 1 for each line and add 1 for each word in a line. So you end up with
data = {
[1] = "object1property1",
[2] = "object1property2",
[3] = "object1property3"
}
Instead of the intended
data = {
PropertyKey1 = "object1property1",
PropertyKey2 = "object1property2",
PropertyKey3 = "object1property3"
}
So you probably meant to write
local key = headers[headerkey]
data[key] = word
But you have to move headers out of the loop. Otherwise you'll end up with an empty table for line 1 resulting in key being nil which would cause Lua errors for using a nil table index.
The following line is called for every word
table.insert(OutTable, data)
You need to do this for every line!
Your code basically produces this output:
local tableA = {"object1property1", "object1property2", "object1property3"}
local tableB = {"object2property1", "object2property2", "object2property3"}
local tableC = {"object3property1", "object3property2", "object3property3"}
OutTable = {
tableA, tableA, tableA, tableB, tableB, tableB, tableC, tableC, tableC
}
I suggest you formulate your program in your first language and then translate it into Lua. This helps to avoid such errors.
Your problem is not related to metatables, classes or anything else mentioned. You simply used the wrong variable and messed up your inner loop.

Why is "Input string was not in a correct format." in the query in mySQL?

In the following code,
I get a run time error of
"Input string was not in a correct format." after oCommand.ExecuteReader().
oCommand.CommandText = "CheckOutItem";
oCommand.CommandType = System.Data.CommandType.StoredProcedure;
oCommand.Parameters.AddWithValue("#OrderID", OrderID);
oCommand.Parameters.AddWithValue("#GivenLargeSizeName", Enum.GetName(typeof(Size), Size.REGULAR));
oCommand.Parameters.AddWithValue("#GivenSmallSizeName", Enum.GetName(typeof(Size), Size.SMALL));
oCommand.Parameters.AddWithValue("#Latitude",oOrder.OrderTimeLocation.Location.latitude);
oCommand.Parameters.AddWithValue("#Longitude",oOrder.OrderTimeLocation.Location.longitude);
oCommand.Parameters.AddWithValue("#ListingID", MySqlDbType.Int64);
oCommand.Parameters.AddWithValue("#Quantity", MySqlDbType.Int16);
oCommand.Parameters.AddWithValue("#Size", MySqlDbType.VarChar);
oCommand.Parameters.AddWithValue("#DeliveryMethod", MySqlDbType.VarChar);
foreach (var OrderItem in oOrder.OrderItems)
{
oCommand.Parameters["#ListingID"].Value = OrderItem.ListingID;
oCommand.Parameters["#Quantity"].Value = OrderItem.Quantity;
oCommand.Parameters["#Size"].Value = Enum.GetName(typeof(Size), OrderItem.Size);
oCommand.Parameters["#DeliveryMethod"].Value = Enum.GetName(typeof(DeliverMethod), OrderItem.DeliveryPickupMethod);
using (var reader = oCommand.ExecuteReader())
{
while (reader.Read())
{
Int64 OrderItemID = Convert.ToInt64(reader["#ORDER_ITEM_ID"]);
Int64 OrderItemStatusID = Convert.ToInt64(reader["#ORDER_ITEM_STATUS_ID"]);
Int64 OrderItemPriceID = Convert.ToInt64(reader["#ORDER_ITEM_PRICE_ID"]);
TotalOrderCostFromDB = TotalOrderCostFromDB + Convert.ToDecimal(reader["#TOTAL_ORDER_COST"]);
}
}
}
if I use statements like
oCommand.Parameters.AddWithValue("#ListingID",OrderItem.ListingID)
works fine but I can not loop.
All the values I am assigning are correct in debugging and no nulls or weird stuff getting into .Value.
Since I get the correct answer in AddWithValue method, I don't think I have any issue with StoredPoocedure.
Is there a better approach to loop for this purpose?
After some debugging, I was able to narrow down the issues to last two lines
oCommand.Parameters.AddWithValue("#Size", MySqlDbType.VarChar);
oCommand.Parameters.AddWithValue("#DeliveryMethod", MySqlDbType.VarChar);
If I initialize this with a dummy string, everything is fine. But initializing with VarChar or String cause problems.
For my understanding, following returns a string right?
Enum.GetName(typeof(Size), OrderItem.Size)

Load 3D model in Unity using Resource folder and Mysql

I want to load 3D model using Resource folder. I created an sql database to store the address. In this case I stored the file "deer-3ds" in folder "Models" and also save these information in a table named "modeladdress" in sql.
So please help me to correct my code. I know that it's 100% wrong but I dont know how to fix it. Thank you.
using UnityEngine;
using System.Collections;
using System;
using System.Data;
using Mono.Data.Sqlite;
public class addobject : MonoBehaviour {
// Use this for initialization
void Start () {
//GameObject deer=Instantiate(Resources.Load("deer-3d.bak",typeof(GameObject)))as GameObject;
// GameObject instance = Instantiate(Resources.Load("Models/deer-3ds", typeof(GameObject))) as GameObject;
string conn = "URI=file:" + Application.dataPath + "/modeladdress.s3db"; //Path to database.
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT ordinary,foldername, filename " + "FROM modeladdress";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read ()) {
int ordinary = reader.GetInt32 (0);
string foldername = reader.GetString (1);
string filename = reader.GetString (2);
string path = foldername + "/" + filename;
//Debug.Log( "value= "+value+" name ="+name+" random ="+ rand);
GameObject instance = Instantiate(Resources.Load(path, typeof(GameObject))) as GameObject;
instance.SetActive (true);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
// Update is called once per frame
void Update () {
// GameObject instance = Instantiate(Resources.Load("Models/deer-3ds", typeof(GameObject))) as GameObject;
// instance.SetActive (true);
}
}
First of all, you are using SQLite at your database management system, not MySQL. Second, the way you have written your query,
string sqlQuery = "SELECT ordinary,foldername, filename " + "FROM modeladdress";
Will return the ordinary, foldername, and filename for every model. You need to use a WHERE clause to specify precisely which model you want to use. Thus, you need some way to know which model you want to query from the database before you actually execute the query, and in that case, why even query a database? You're going to have to store some unique identifier anyway so a database solves nothing.
Now concerning the actual code you have written, it appears to be correct (i.e. it should be returning what you want). The problem must be that either your table is empty, your values that are returned are incorrect, or that the object is being instantiated in an incorrect location and thus you are thinking it's not working. If you want a more concrete answer you'll have to comment on this answer with the specific problem you are facing (i.e. what specifically is "wrong"?).

Error in quick start guide

I'm new to encog, and I recently read the "Quick Start Guide"
However I found a things that I consider an error, can you confirm this?
In the final "chapter", "Using Encog for Time Series", the output is printed in the console using this code:
while (csv.next() && stopAfter > 0) {
StringBuilder result = new StringBuilder();
line[0] = csv.get(2);// ssn
line[1] = csv.get(3);// dev
helper.normalizeInputVector(line, slice, false);
// enough data to build a full window?
if (window.isReady()) {
window.copyWindow(input.getData(), 0);
String correct = csv.get(2); // trying to predict SSN.
MLData output = bestMethod.compute(input);
String predicted = helper
.denormalizeOutputVectorToString(output)[0];
result.append(Arrays.toString(line));
result.append(" -> predicted: ");
result.append(predicted);
result.append("(correct: ");
result.append(correct);
result.append(")");
The wrong I think it is wrong, is the "correct" variable: since it is predicting the SSN value from the CSV, it is right to read it using csv.get(2), but it should be invoked on time "t+1". In this code it is evaluated equals to SSN at time t
The output shows this too:
[9.4, 9.1] -> predicted: 16.576461298905144(correct: 9.4)
here it is clear that "correct" value is the same as input.
Am I missing anything?
thanks
A.

How to delete multiple rows (using named parameters) in Adobe AIR

I am trying to delete multiple rows in the sqlite table in my Adobe AIR app (runtime 2.5).
Here is the statement, using the "IN" operator:
"DELETE FROM mylist WHERE tdId IN (tdId1, tdId2, tdId3, ...)";
Where tdId1, tdId2, etc. will be determined at runtime based on which row(s) the user chooses to delete. The user can delete arbitrary number of rows.
I've tried something like:
//delete statement text
"DELETE FROM mylist WHERE tdId IN :tdId";
//delete statement parameters: take 1.
//Got "argument error: near ':tdId': syntax error"
deleteStmt.parameters[":tdId"] = "(26, 32)";
//delete statement parameters: take 2.
//Also got "argument error: near ':tdId': syntax error"
var arr:Array = [26, 32];
deleteStmt.parameters[":tdId"] = arr;
How I go about deleting multiple rows?
[Edit] So it looks like the aforementioned cached statement with parameter [":tdId"] doesn't work when deleting multiple rows. When attempting to execute the delete statement multiple times in asynchronous mode, after the very first row in the queue is deleted, Flash throws the following error:
"Error #3110: Operation cannot be
performed while SQLStatement.executing
is true."
It would seem too much of trouble to chain these deletes with a callback. So I guess I am using my last resort: building the sql at runtime. Conclusion: Cached statements can't be used in these kind of situations...
The problem occurs when you insert the parameter "(26,32)". As the parameter is not purely a substitution of value, it represents a variable to SQL, NOT A STRING. Hence you statement effectively became (or roughly) in your first take...
"DELETE FROM mylist WHERE tdId IN '(26,32)'"
Hence your error, due to the syntax... In your second take it gets worse...
"DELETE FROM mylist WHERE tdId IN *Array(26,32)*"
As the variable does not convert to a string value, this does not actually happen. But what happens is that when the interprater (SQL) tries to understand the code after the 'IN' text, it gets an ARRAY object, which it has completely no idea on what to do... Its not even a valid SQL type....
Solution? [I yet to fully test it, so please do]
var toDel:Array = [26,32]
//delete statement text
var baseStr:String = "DELETE FROM mylist WHERE tdId IN (";
var midStr:String = '';
//delete statement parameters: Processing parameter
for( var i = 0; i < toDel.length; i++ ) {
deleteStmt.parameters[i] = toDel[i];
if(midStr.length > 0) { midStr += ' , '; }
midStr += '?';
}
deleteStmt.text = baseStr + midStr + ' )';
//Then execute
So what happens in this case is that u effectively execute...
"DELETE FROM mylist WHERE tdId IN ( :val1 , :val2 )"
In this way you still maintain the safe (good practice) use of parameters, without converting everything to a string.
EDIT: if you dun understand the use of parameter / '?' refer to :
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/data/SQLStatement.html#parameters
If the IN clause does not allow parameters, you can try old-school SQL style: append multiple
" OR (tdId = :param" + paramCounter.toString() + ")"
to the SQL string