I am trying to fetch data from my database giving it only an ID number. My database has 2 columns, first is ID, and second is an image path.
so if i pass ID=3, it should return the path corresponding to that ID.
I have tried to do that, but I am stuck at query.
mysql_query (conn, "SELECT * FROM table" );
res = mysql_use_result(conn);
row = mysql_fetch_row(res)
ID = atoi(row[0]);
path = row[1];
printf("ID: %i", ID);
printf("Image Path: %s", path);
Please help:)
I think the question is not really clear. First case, for each row you want to display id/path:
mysql_query (conn, "SELECT * FROM table" );
res = mysql_use_result(conn);
while (row = mysql_fetch_row(res)) {
ID = atoi(row[0]);
path = row[1];
printf("ID: %i", ID);
printf("Image Path: %s", path);
}
Other possibility, you want only one row because you know the ID you are looking for. Then you can decide to retrieve only the missing column with something like:
mysql_query (conn, "SELECT path FROM table WHERE id=ID" );
In some more complicated cases, lets say even if with the WHERE you may have multiple rows, you can keep only the first one for example by adding the TOP condition in your query. In any cases you need to think on what will be returned for real.
I didn't test the code I wrote, just edited a bit what you posted (just to be fair ^^)
You seem to have a few problems with basic computer concepts. For instance, the concept of having one thing versus more things. You fetch one row, but your database table has multiple rows and your query returns all rows. (No WHERE clause).
The obvious solution is to either fetch all rows, or (better) restrict your query to just the row you want.
Related
I'm creating a report table type calendar where users can create back up by date select a filter that would filter out the table values depending on the user selected. (i.e. if they choose user1, then only back ups with user1 will show up)
I would like it to be when P106_BACK_UP_BY_USER = 0, the table shows all the values (aka getting rid of the "where" portion of the query.
Thank you for your help!
I'm having issues with trying to allow the user to see all the back ups of the table again (getting rid of the filtered value). My current query is this:
I would like it to be when P106_BACK_UP_BY_USER = 0, the table shows all the values (aka getting rid of the "where" portion of the query.
Thank you for your help!
You can use case when statements in your query's where condition as follows:
select *
from my_table
where my_table.created_by =
(select user_name from my_table2 where app_users_id =
case :P106_BACKUP_BY_USER when 0 then app_users_id
else :P106_BACKUP_BY_USER
end)
And for getting better help, please paste your code as text not as an image next time.
This should work too:
...
WHERE b.active_server = s.server_id
AND (:P106_BACK_UP_BY_USER = 0 OR
UPPER(b.created_by) =
(SELECT UPPER(user_name)
FROM eba_bt_app_users
WHERE app_users_id = :P106_BACK_UP_BY_USER
)
);
Good evening people,
I am building a database using SQLite3 and C++ and I want to insert into table "Subs" as a foreign key, the ID which is the primary key for table "Programs". The table Programs has two columns, Id and programCode. I have the programCode in a variable so my approach is to get the Id from the programCode, store it into a variable and then store this in the table Subs. My problem is that I don't know how to get the result from query and store it into a variable. This is my code:
sqlite3_stmt *sql;
rc = sqlite3_prepare_v2(db, "SELECT Id FROM Programs WHERE programCode=?", -1, &sql, 0);
sqlite3_bind_text(sql, 1, _program.c_str(), -1, SQLITE_TRANSIENT);
int step = sqlite3_step(sql);
if(step == SQLITE_ROW) {
printf("%d\n", sqlite3_column_int(sql, 0));
}
The _program variable holds the programCode value.
Printf prints nothing and I expected to see the result of the query so I can use this to store it into an integer.
Any help would be highly appreciated.
Thanks to #CL for giving me this piece of information. I checked my csv where I retrieve the information for the database and the programCode had a "space" before the text so that is why there was no matching row. Thanks #CL!
I´m having the following code that insert a row into mysql database and return the inserted id:
/*
* Execute the statement
*/
std::string sql = "INSERT INTO TABLE (A, B, C) VALUES (1, 2, 3)";
sql::Statement *stmt;
stmt = connection->createStatement();
stmt->execute(sql);
/*
* Get the returned id
*/
stmt = connection->createStatement();
sql::ResultSet *res = stmt->executeQuery("SELECT ##identity AS id");
res->next();
model.modelId = res->getInt64("id");
My questions are:
Do I really need to call connection->createStatement() again ?
I think this may overload the code, as I need to call twice the database.
Is there a way to optimize this code ?
Is there other way to get the last inserted id ?
Thanks for helping.
Just for the reference, ##identity is MSSQL-specific system function, that also returns last-insert id but for MSSQL, not for MySQL.
To get last-insert id in MySQL, since you have asked specifically for MySQL, you need to change your SELECT statement to following:
SELECT LAST_INSERT_ID() AS id;
Also, since stmt->execute() and stmt->executeQuery() methods take String, as input argument, I am sure that you don't need to connection->createStatement() again. Just to confirm, I just googled it and found this link.
Please note that this answer is specifically for MySQL, as this question is about MySQL. Hope it helps.
Using Qt, I have to connect to a database and list column's types and names from a table. I have two constraints:
1 The database type must not be a problem (This has to work on PostgreSQL, SQL Server, MySQL, ...)
2 When I looked on the internet, I found solutions that work but only if there are one or more reocrd into the table. And I have to get column's type and name with or without record into this database.
I searched a lot on the internet but I didn't find any solutions.
I am looking for an answer in Qt/C++ or using a query that can do that.
Thanks for help !
QSqlDriver::record() takes a table name and returns a QSqlRecord, from which you can fetch the fields using QSqlRecord::field().
So, given a QSqlDatabase db,
fetch the driver with db.driver(),
fetch the list of tables with db.tables(),
fetch the a QSqlRecord for each table from driver->record(tableName), and
fetch the number of fields with record.count() and the name and type with record.field(x)
According to the previous answers, I make the implementation as below.It can work well, hope it can help you.
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSLITE", "demo_conn"); //create a db connection
QString strDBPath = "db_path";
db.setDatabaseName(strDBPath); //set the db file
QSqlRecord record = db.record("table_name"); //get the record of the certain table
int n = record.count();
for(int i = 0; i < n; i++)
{
QString strField = record.fieldName(i);
}
}
QSqlDatabase::removeDatabase("demo_conn"); //remove the db connection
Getting column names and types is a database-specific operation. But you can have a single C++ function that will use the correct sql query according to the QSqlDriver you currently use:
QStringlist getColumnNames()
{
QString sql;
if (db.driverName.contains("QOCI", Qt::CaseInsensitive))
{
sql = ...
}
else if (db.driverName.contains("QPSQL", Qt::CaseInsensitive))
{
sql = ...
}
else
{
qCritical() << "unsupported db";
return QStringlist();
}
QSqlQuery res = db.exec(sql);
...
// getting names from db-specific sql query results
}
I don't know of any existing mechanism in Qt which allows that (though it might exist - maybe by using QSqlTableModel). If noone else knows of such a thing, I would just do the following:
Create data classes to store the information you require, e.g. a class TableInfo which stores a list of ColumnInfo objects which have a name and a type.
Create an interface e.g. ITableInfoReader which has a pure virtual TableInfo* retrieveTableInfo( const QString& tableName ) method.
Create one subclass of ITableInfoReader for every database you want to support. This allows doing queries which are only supported on one or a subset of all databases.
Create a TableInfoReaderFactory class which allows creation of the appropriate ITableInfoReader subclass dependent on the used database
This allows you to have your main code independent from the database, by using only the ITableInfoReader interface.
Example:
Input:
database: The QSqlDatabase which is used for executing queries
tableName: The name of the table to retrieve information about
ITableInfoReader* tableInfoReader =
_tableInfoReaderFactory.createTableReader( database );
QList< ColumnInfo* > columnInfos = tableInfoReader->retrieveTableInfo( tableName );
foreach( ColumnInfo* columnInfo, columnInfos )
{
qDebug() << columnInfo.name() << columnInfo.type();
}
I found the solution. You just have to call the record function from QSqlDatabase. You have an empty record but you can still read column types and names.
I'm using the sqlite3 library in c++ to query the database from *.sqlite file. can you write a query statement in sqlite3 like:
char* sql = "select name from table id = (select full_name from second_table where column = 4);"
The second statement should return an id to complete the query statement with first statement.
Yes you can, just make sure that the nested query doesn't return more than one row. Add a LIMIT 1 to the end of the nested query to fix this. Also make sure that it always returns a row, or else the main query will not work.
If you want to match several rows in the nested query, then you can use either IN, like so:
char* sql = "select name from table WHERE id IN (select full_name from second_table where column = 4);"
or you can use JOIN:
char* sql = "select name from table JOIN second_table ON table.id = second_table.full_name WHERE second_table.column = 4"
Note that the IN method can be very slow, and that JOIN can be very fast, if you index on the right columns
On a sidenote, you can use SQLiteadmin (http://sqliteadmin.orbmu2k.de/) to view the database and make queries directly in it (useful for testing etc).