Replacing table name with a variable in a query - c++

i have the following code.My table is called 'tableu'.I want replace 'tableu' with a variable that will hold the table name. How can i represent that.
query.prepare(
"INSERT INTO tableu (village, weight, diet, age)"
"VALUES (:village, :weight, :diet, :age)"
);

If you want to change your table name from tableu to lets say NewTableName, it can be done using any of the following syntax:
query.prepare(
"RENAME tableu TO NewTableName"
);
OR
query.prepare(
"ALTER TABLE tableu RENAME TO NewTableName"
);
Update:
May be the OP is looking for this.
QString tableName = QString("tableu");
QString sqlQuery = QString("INSERT INTO %1 (village, weight, diet, age) VALUES (:village, :weight, :diet, :age)").arg(tableName);

I'm not 100% sure what you want, but this code will let you have a variable that may contain different tables names placed in the query
char sBuffer [1024];
char sQueryTable[] = "tableu";
sprintf(sBuffer , "INSERT INTO %s (village, weight, diet, age) VALUES (:village, :weight, :diet, :age)", sQueryTable);
query.prepare(sBuffer);
Read about sprinft and formatting strings here
Note: you can always use std::strings as well and concatenate the string together from a variable holding your table name and the rest of the string

Related

How can I insert string value from .csv to SQLite database? Qt c++

This code can successfully insert an integer value from the .csv file to the SQLite database. However, when the value is a string. It does not insert the string value. Please help.
QFile f(csvFile);
if(f.open (QIODevice::ReadOnly)){
QSqlQuery que;
QTextStream ts (&f);
//Travel through the csv file "excel.csv"
while(!ts.atEnd()){
QString req = "INSERT INTO main VALUES(";
QStringList line = ts.readLine().split(',');
for(int i=0; i<line .length ();++i){
req.append(line.at(i));
req.append(",");
}
req.chop(1); // remove the trailing comma
req.append(");"); // close the "VALUES([...]" with a ");"
que.exec(req);
qDebug()<<req;
que.lastError();
}
qDebug()<< req ouput:
"INSERT INTO main VALUES(1,2,3);" "INSERT INTO main VALUES(a,b,c);"
Based on Prapin's answer I've decided to write up a quick how to.
Here is the link to QTs SQL statement documentation. There are multiple ways in which to query the database. I personally am a fan of #2 'named binding' over #3 'positional binding'. This is because it is very clear to the programmer what values are being accessed.

Creating a char* of specific format with specific values

I am attempting to create a char* type in a specific format, using values given by the other areas of the program, the values within the VALUES() brackets are the values that are given by the program.
The format should look like so:
char* sql = "INSERT INTO RecurringEvents (title,description,duration,recurtype,startfrom,endingtype,dateend,occurences,venueid) " \
"VALUES ('title','description','duration','recurtype','startfrom','endingtype','dateend',occurences,venueid); "
As you can see, text values must be within ' ' punctuation, while int values are left alone, so a usual command may be like so:
"INSERT INTO RecurringEvents (title,description,duration,recurtype,startfrom,endingtype,dateend,occurences,venueid) " \
"VALUES ('thetitle','thedesc','theduration','recurtype','startfrom','enddddtype','dateend',2,4); ";
The function in which this is required is below,not that it all matters, but to explain, it converts the event's(class) data all into string/int values, so they can be used to form an INSERT command(this is the proble), and then executed on a database, once this is done (and the record is verified for plausability) its added to the vector and the database is closed.
void addRecEvent(newRecurringEvent event, vector <newRecurringEvent> &events){
sqlite3 *db;
int rc;
char *sql;
int tableCheck;
char *zErrMsg = 0;
rc = sqlite3_open("data.sqlite", &db);
string title = event.getTitle();
string description = event.getDescription();
string duration = to_string(event.getDuration());
string recurType = recToString(event.getRecurType());
string startfrom = to_string( event.getStartFrom());
string endingtype = etypeToStr(event.getEndingType());
string dateend = to_string(event.getDateEnd());
int occurences = event.getOccurences();
int venueid = event.getVenuid();
/*CREATE INSERT COMMAND USING char*sql IN FORMAT REQUIRED*/
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); //execute the command
if (rc != SQLITE_OK){
cout << stderr << "SQL error: %s \n", zErrMsg;
}
else{
cout << stdout << "Records created succesfully";
events.push_back(event);
}
sqlite3_close(db);
}
I once attempted to create the format all in string within another function (by passing the values to it), and then returning it as a char*, but came accross the problem of the single quotation marks used on the text fields (like title,description etc).
Sorry if any of this is confusing, but to make it short, I just want to form a character sequence in the format in the first snippet of code, that uses given values to form its sequence.Any help is appreciated, as I am new to c++.
The comment left by whozcraig solved my question, I must use a prepared statement to feed my values to the statement

How to use variables in query

I have to use a user input value in my query to select a row which has that value........
I have written this code in qt but it doesn't work...how can I fix it?
void MainWindow::on_pushButton_clicked()
{
int j=0;
float t;
t=ui->T_lineEdit->text().toFloat();
QSqlQuery qry;
if(qry.exec("select * from table where te='+t+'"))
{
ui->u_lineEdit->setText("hello");
}
}
You should use a prepared statement using QSqlQuery.
QSqlQuery qry;
qry.prepare("select * from table where te=?");
qry.addBindValue(t);
if(qry.exec())
{
ui->u_lineEdit->setText("hello");
}
Note that concatenating user's raw string to a SQL query is highly vulnerable to SQL Injection.
I'm not familliar with qt, but it seems to me that you used concatenation within a string, so "select * from table where te='+t+'" should be "select * from table where te='"+t+"'" .
Of course it is strange that you should place single quotes around a float value, but I don't know the type of column te. It could be necessary to convert t to string first:
"select * from table where te='" + QString::number(t) + "'"
Finally I have to add that this looks suspiciously like code where you allow SQL Injection. You should look into this and make sure to avoid it. See Frogatto's answer for that.

How to perform IN in sql query using pqxx in c++ for postgresql?

How to perform IN in sql query using pqxx in c++ for postgresql ?
I have vector<long> of ids and I need to update every row in table students ( to set faculty_id to some new value).
I want to avoid loop, new value (faculty_id) I get when I insert faculty with prepared INSERT statement.
Is possible at all to pass so iterable structure or create prepared IN query using pqxx ?
void prepareChangeFaculty(connection_base &c){
const std::string sql =
"UPDATE students SET faculty_id=$2 WHERE id IN $1"; // here is a problem
c.prepare("change_faculty", sql);
}
$1 I have like vector of id of rows which I need to update
Why not something like that (How to concatenate a std::string and an int?) in C++11
string a="";
for (int k=0;k<myVector.size();k++){
a += string(myVector[k]);
if (k<myVector.size()-1){
a += ",";
}
}
std::string sql = "UPDATE students SET faculty_id=$2 WHERE id IN (" + a + ")";
I understand the concerns of #Massa, however I could not find a different solution than the #Alexandros one.
So, a bit improvement to this solution can be the use of std::copy
std::stringstream params;
std::copy(
myVector.begin(), myVector.end(),
std::ostream_iterator<std::string>(params, ","));
std::string sql = "UPDATE students SET faculty_id=$2 WHERE id IN ('"
+ params.str() + "')";

C++ sql pass integer to sql string

I have built a database in MS Access.
There I have a table called Customers which also has a cell called Employee type: integer.
I also built a program in C++ which controls all data.
Let's say I have a string like this:
string sqlString = "SELECT * FROM Customers Where Customers.Employee = '" + id + "' ";
Id passes through my function correctly and is an integer, so I get an error in compilation saying: "Invalid pointer addition".
If I declare id as a string of course there's no error but there are no results in my form also. If I declare in database cell Employee as text and build my query like this:
string sqlString = "SELECT * FROM Customers WHERE Customers.Employee = 128";
I get results, but I need that Employee as an integer cause its a foreign key from another table.
So, what should I do with my query to have results passing integer as parameter through variable id, to be ok with the cell Employee from database which is also integer?
Any ideas? I would really appreciate some help here.
As I said, if I convert id to string, there are no results in my form since Employee in database is an integer. So this:
std::ostringstream buf;
buf << "SELECT * FROM Customers Where Customers.Employee = '" << id << "' ";
string str = buf.str();
won't do the job or any other conversion.
How can I pass id as an integer in my query?
You could use sprintf, but in C++ you can do:
std::ostringstream buf;
buf << "SELECT * FROM Customers Where Customers.Employee = '" << id << "' ";
string str = buf.str();
(untested)
You need to convert id to a string, then your first approach should work.
See this question for how to do the conversion:
Alternative to itoa() for converting integer to string C++?
use
std::ostringstream buf; buf << "SELECT * FROM Customers Where Customers.Employee = " << id ; string str = buf.str();
This should work please try '12' --- quote should not be placed before and after 12
you can use boost::format with boost::str
string = boost::str(boost::format("This is a string with some %s and %d numbers") %"strings" %42);
this should be better approach since you will have all the replacement variable in one place at the end.