I want to do a prepared statement like this:
pstmt=conn->prepareStatement("UPDATE partidos SET i?=? WHERE ID=?");
pstmt->setInt(1,lazo);
pstmt->setString(2,texto[lazo]);
pstmt->setInt(3,var);
pstmt->execute();
"lazo" is a variable in a for loop, texto[lazo] is a variable and var is another int variable.
When I run this query, it throws an exception: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'i?=? WHERE ID=?' at line 1".
It seems that it doesn't replace the '?'.
I tried with stringstreams, but the problem didn't fix.
Thanks.
Finally I opted for this.
stringstream stmtvar;
stmtvar << "UPDATE PARTIDOS SET minuto" << lazo << "='" << texto[lazo] << "' WHERE ID=" << var;
stmt->executeUpdate(stmtvar.str());
It worked perfectly
Related
I am performing queries against a MySQL database, and use code similar to below throughout my app. But for some reason the update below says 0 rows affected, when it should be 1. On digging deeper I discovered my bindValue commands don't seem to have any effect.
QSqlQuery* query = new QSqlQuery(m_db)
query->prepare(QString("UPDATE companies SET "
"NAME=:name, "
"ISUSER=:isuser, "
"ISVAR=:isvar, "
"ISOEM=:isoem, "
"CONTACT=:contact, "
"EMAIL=:email, "
"COMMENTS=:comments "
"WHERE ID=:id "
"LIMIT 1"));
query->bindValue(":name",rowData.name);
query->bindValue(":isuser",rowData.isEndUser);
query->bindValue(":isvar",rowData.isVAR);
query->bindValue(":isoem",rowData.isOEM);
query->bindValue(":contact",rowData.contact);
query->bindValue(":email",rowData.email);
query->bindValue(":comments",rowData.comments);
query->bindValue(":id",id);
bool queryOk = query->exec();
if (queryOk) {
qDebug() << query->executedQuery();
qDebug() << query->lastQuery();
qDebug() << query->lastError().text();
qDebug() << rowsAffected;
There must be something different/wrong in the code above causing the output below:
"UPDATE companies SET NAME=:name, ISUSER=:isuser, ISVAR=:isvar, ISOEM=:iSOEM, CONTACT=:contact, EMAIL=:email, COMMENTS=:comments WHERE ID=:id LIMIT 1"
"UPDATE companies SET NAME=:name, ISUSER=:isuser, ISVAR=:isvar, ISOEM=:iSOEM, CONTACT=:contact, EMAIL=:email, COMMENTS=:comments WHERE ID=:id LIMIT 1"
""
0
But I can't see the problem, and the query returns no errors. Yet the query string seems to contain the variable names not substituted.
QSqlQuery::executedQuery() won't show you the bound values, because the idea of bound values is that they never become part of the query itself (which completely eliminates the problem of escaping them). What you see is the actual query submitted to the database. The bound values are submitted to the database alongside the query string (very much same like with QSqlQuery).
As for the rowsAffected being zero, I don't see it being initialized or updated by the code in your example, which is likely why it says 0. you probably want to use query->numRowsAffected() instead.
Finally (not related to any of your questions), you don't need to allocate the QSqlQuery on heap (unless you really need the query to outlive the scope in which it is created) and you can simply allocate it on stack. Fewer dynamic allocations == fewer chances of memory leaks :-)
I have a snippet of code from my python 2.7 program:
cur.execute("UPDATE echo SET ? = ? WHERE ID = ?", (cur_class, fdate, ID,))
that when run, keeps throwing the following error:
sqlite3.OperationalError: near "?": syntax error
The program is supposed to insert today's date, into the class column that matches the student ID supplied. If I remove the first "?" like so and hard code the parameter:
cur.execute("UPDATE echo SET math = ? WHERE ID = ?", (fdate, ID,))
everything works just fine. I've googled all over the place and haven't found anything that works yet so I'm throwing out a lifeline.
I've tried single quotes, double quotes, with and without parenthesis and a few other things I can't remember now. So far nothing works other than hard coding that first parameter which is really inconvenient.
As a troubleshooting step I had my program print the type() of each of the variables and they're all strings. The data type of the the cur_class field is VARCHAR, fdate is DATE, and ID is VARCHAR.
Thanks to the tip from #Shawn earlier I solved the issue with the following code and it works great:
sqlcommand = "UPDATE echo SET " + cur_class + " = " + fdate + " WHERE ID = " + ID
cur.execute(sqlcommand)
This way python does the heavy lifting and constructs my string with all the variables expanded, then has the db execute the properly formatted SQL command.
I am using JSON format to save data in my c++ program , i want to send it to MySql database (the table tab has one column with type : TEXT) but the query failed (tested also VARCHAR and CHAR )
this is a part of the code since we are not interrested in the rest
string json_example = "{\"array\":[\"item1\",\"item2\"], \"not an array\": \"asdf\"}";
mysql_init(&mysql); //initialize database connection
string player="INSERT INTO tab values (\"";
player+= json_example;
player += "\")";
connection = mysql_real_connect(&mysql,HOST,USER,PASSWD,DB,0,NULL,0);
// save data to database
query_state=mysql_query(connection, player.c_str()); // use player.c_str()
to show the final query that will be used : cout << player gives :
INSERT INTO tab values ("{"array":["item1","item2"], "not an
array": "asdf"}")
using for example string json_example = "some text"; is working
but with the json format it is not working , maybe the problem came from the use of curly bracket {} or double quotes "" but i haven't find a way to solve it .
i'm using :
mysql Ver 14.14 Distrib 5.5.44, for debian-linux-gnu (armv7l) under raspberry pi 2
Any help will be appreciated , thanks .
Use a prepared statement. See prepared statements documentation in the MySQL reference manual.
Prepared statements are more correct, safer, possibly faster, and keep your code cleaner. You get all those benefits and don't need to escape anything. There is hardly a reason not to use them.
Something like this might work. But take it with a grain of salt, because I have not tested or compiled it. It should just give you the general idea:
MYSQL_STMT* const statement = mysql_stmt_init(&mysql);
std::string const query = "INSERT INTO tab values(?)";
mysql_stmt_prepare(statement, query, query.size());
MYSQL_BIND bind[1] = {};
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = json_example.c_str();
bind[0].buffer_length = json_example.size();
mysql_stmt_bind_param(statement, bind);
mysql_stmt_execute(statement);
I am trying to insert a entry into a table but the server says this
column "Date" is of type date but expression is of type integer at character 131
This is the SQL statement I can also show the VB.net but it is a horrid mess.
INSERT INTO "Inventory_chemicalrecord"("Barcode","Action","Name_id","Building","Qty","Date") VALUES ('IEN0001','ADD',1,'Marcus',1,2013-07-10);
Here is the String that I am passing
mySQLString = "INSERT INTO "&Chr(34)&"Inventory_chemicalrecord"&Chr(34)&"("&Chr(34)&"Barcode"&Chr(34)& ","&Chr(34)&"Action"&Chr(34)& ","&Chr(34)&"Name_id"&Chr(34)& ","&Chr(34)&"Building"&Chr(34)& "," &Chr(34)&"Qty"&Chr(34)& ","&Chr(34)&"Date"&Chr(34)& ") VALUES ("& code & "," &Chr(39)& Action &Chr(39) & "," & Name_id & "," & Building & ","& OriginalQty & "," & CurDate & ");"
Sorry this is the only way I have found to do this if this is the wrong way to do this please inform me.
I have tried
Chr(39)&CurDate&Chr(39)
"'"&CurDate&"'"
and even set
CurDate = Chr(39)&CurDate&CurDate(39)
I keep getting EOF expected and Type & does not match String
Is there a better way to do this?
The error message is very clear.
The date needs to be wrapped in quotes : '2013-07-10'
INSERT INTO "Inventory_chemicalrecord"("Barcode","Action","Name_id","Building","Qty","Date") VALUES ('IEN0001','ADD',1,'Marcus',1,2013-07-10);
should be
INSERT INTO "Inventory_chemicalrecord"("Barcode","Action","Name_id","Building","Qty","Date") VALUES ('IEN0001','ADD',1,'Marcus',1,'2013-07-10');
I'm trying sqlite3 in my C++ app. I have done:
sqlite3 my.db
sqlite> CREATE TABLE links(UrlAsID VARCHAR(255) PRIMARY KEY, Owner VARCHAR(255), ......, CreationTime INTEGER);
sqlite> CREATE INDEX linkIDs ON links(UrlAsID, CreationTime ASC);
Then I opened a connection from the C++ code to the database.
From within the code I have an Url object. Now I have todo:
// check if url is in index (and in table as well)
string urlID = sqlite3_exec("SELECT UrlAsID FROM linkIDs WHERE UrlAsID = " + Url.id + ";");
if (urlID.empty()) {
sqlite3_exec("INSERT INTO links VALUES (" + Url.properties + ");");
sqlite3_exec("INSERT INTO linkIDs VALUES (" + Url.id + "," + int(Url.creationTime) + ");");
} else {
sqlite3_exec("UPDATE links SET (CreationTime = " + int(Url.creationTime) + "," + ... + ") WHERE UrlAsID = " + Url.id + ";");
sqlite3_exec("UPDATE linkIDs SET (CreationTime = " + int(Url.creationTime) + ") WHERE UrlAsID = " + Url.id + ";");
}
I thought to create a stored procedure or to use a complex SQL statement to encapsulate the above logic. Could you please provide me with more precise code to accomplish this.
Thank you in advance!
Your statements should be wrapped in a transaction for both safety and speed. Furthermore, you should use prepared statements with parameters, again for both safety and speed (different sort of safety, but even so). And you should use INSERT OR REPLACE with a suitable COALESCE. All of this is irrespective of which language you're embedding within, but the links are to relevant syntax.
SQLite doesn't support stored procedures: http://www.sqlite.org/whentouse.html
If the SQL code is complex I would try to put in a .sql file, then load into a variable and execute.
SQLite does not support stored procedures. The most you can do is use prepared statements. You should also use the SQLite binding methods to set parameters, instead of string concatenation. Read the introduction here: http://sqlite.org/cintro.html