Sqlite DB Error - could not prepare statement - sqlite

I am getting following error on insert statement for sqlite DB
could not prepare statement (1 near "undefined": syntax error)
I tried 2 variations of insert, for both error is same
var sql = "INSERT INTO Med(MedID) VALUES(?),";
sql += "['"+dataObj[i].MedID+"']";
var sql = "INSERT INTO Med(MedID) VALUES ('"+dataObj[i].MedID+"')";
tx.executeSql(sql);

The correct way to give parameters to an SQL statement is as follows:
var sql = "INSERT INTO Med(MedID) VALUES (?)";
tx.executeSql(sql, [dataObj[i].MedID]);

It looks like you are missing the space that is needed between the table name and the column names.
Try this:
var sql = "INSERT INTO Med (MedID) VALUES ('"+dataObj[i].MedID+"')";
tx.executeSql(sql);
Make sure your dataObj[i].MedID is also defined. Add a console.log(sql) before your executeSql statement to check the command before using it.

Related

Mariadb syntax error on Declare statement

I am creating a MariaDB stored procedure in phpmyAdmin and I keep getting a syntax error.
I have tried appending an # symbol for the variable but I am still getting the error.
Here is what my code currently looks like:
DECLARE #cNAME = VARCHAR(100);
SET #cNAME = "TEST";
SELECT * from tblUser where UserName = cNAME;
I expect that my stored procedure would get saved but it doesn't because of the syntax error.

Add dictionary or list to Sqlite3 - Gives error operation parameter must be str

Ok I am new to sqlite and python in general so please be nice =)
I have a simple dictionary -
time = data[0]['timestamp']
price = data[0]['price']
myprice = {'Date':time,'price':price}
myprice looks like this (time is a timestamp) -
{'Date': 1553549093, 'price': 1.7686}
I now want to add the data to sqlite3 database...so I created this -
#Create database if not exist...
db_filename = 'mydb_test.db'
connection = sqlite3.connect(db_filename)
#Get a SQL cursor to be able to execute SQL commands...
cursor = connection.cursor()
#Create table
sql = '''CREATE TABLE IF NOT EXISTS TEST
(PID INTEGER PRIMARY KEY AUTOINCREMENT,
DATE TIMESTAMP,
PRICE FLOAT)'''
#Now lets execute the above SQL
cursor.execute(sql)
#Insert data in sql
sql2 = ("INSERT INTO GBPCAD VALUES (?,?)", [(myprice['Date'],myprice['price'])])
cursor.execute(sql2)
cursor.commit()
connection.close()
But when executing this code I get ValueError: operation parameter must be str
What am I doing wrong?
Pass the arguments of the insert statement in execute():
sql2 = "INSERT INTO GBPCAD (DATE, PRICE) VALUES (?,?)"
cursor.execute(sql2, (myprice['Date'], myprice['price']))
Also include in the insert statement the names of the columns.

Creating a new table in sqlite database [duplicate]

I'm having some strange feeling abour sqlite3 parameters that I would like to expose to you.
This is my query and the fail message :
#query
'SELECT id FROM ? WHERE key = ? AND (userid = '0' OR userid = ?) ORDER BY userid DESC LIMIT 1;'
#error message, fails when calling sqlite3_prepare()
error: 'near "?": syntax error'
In my code it looks like:
// Query is a helper class, at creation it does an sqlite3_preprare()
Query q("SELECT id FROM ? WHERE key = ? AND (userid = 0 OR userid = ?) ORDER BY userid DESC LIMIT 1;");
// bind arguments
q.bindString(1, _db_name.c_str() ); // class member, the table name
q.bindString(2, key.c_str()); // function argument (std::string)
q.bindInt (3, currentID); // function argument (int)
q.execute();
I have the feeling that I can't use sqlite parameters for the table name, but I can't find the confirmation in the Sqlite3 C API.
Do you know what's wrong with my query?
Do I have to pre-process my SQL statement to include the table name before preparing the query?
Ooookay, should have looked more thoroughly on SO.
Answers:
- SQLite Parameters - Not allowing tablename as parameter
- Variable table name in sqlite
They are meant for Python, but I guess the same applies for C++.
tl;dr:
You can't pass the table name as a parameter.
If anyone have a link in the SQLite documentation where I have the confirmation of this, I'll gladly accept the answer.
I know this is super old already but since your query is just a string you can always append the table name like this in C++:
std::string queryString = "SELECT id FROM " + std::string(_db_name);
or in objective-C:
[#"SELECT id FROM " stringByAppendingString:_db_name];

Android SQLITE Insert into table with values coming from a subquery

In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery.
The insert into statement may look like the following example:
INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))
At present I am doing it manually building the query:
String MyQuery = "INSERT INTO mytable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String
SQLiteDatabase= db = getWritableDatabase();
db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock
What i would like to do instead is:
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));
db.insert("MyTable", null, values);
db.close();
Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement.
Is there a way to achieve this?
The whole point of the ContentValues container is to be able to safely use strings without interpreting them as SQL commands.
It is not possible to use subqueries with insert(). The only way to get a value from another table is by executing a separate query; in this case, ThisIsAQuery() would be stringForQuery() or longForQuery().

Strange result with

When i run this as my first commend i get an exception an error near "last_insert_rowid". This is referring to the last last_insert_rowid();. If i set the curser to the line command.CommandText = and run it again it is fine.
What gives? The last_insert_rowid seems to be working properly why doesnt the last_insert_rowid after the 2nd insert work.
I tried moving last_insert_rowid() to after the execute and i still get an error. What gives?
using (var trans = connection.BeginTransaction())
{
command.CommandText =
"INSERT INTO link_list(link, status, hash_type, hash_id) " +
"VALUES(#link, #status, #hash_type, #hash_id);" +
"INSERT INTO active_dl(linkId, orderNo) " +
"VALUES(last_insert_rowid(), (SELECT COUNT(*) FROM active_dl)); last_insert_rowid();";
command.Parameters.Add("#link", System.Data.DbType.String).Value = link;
command.Parameters.Add("#status", System.Data.DbType.Int32).Value = SiteBase.Status.none;
command.Parameters.Add("#hash_type", System.Data.DbType.Int32).Value = 0;
command.Parameters.Add("#hash_id", System.Data.DbType.Int32).Value = 0;
int rowid = command.ExecuteNonQuery();
trans.Commit();
}
Why is the last last_insert_rowid() there? After the second insert you call last_insert_rowid with no select or anything to identify what you want to do with it.
You would have to put a select in front of it to retrieve the value wouldn't you?
You're trying to execute 2 sql commands in the one statement. You'll need to split the 2 statements up into 2 calls and return the inserted id from the first statement.
An alternative suggestion is a stored procedure but I don't think sqlite supports these.

Resources