Using C++ and MariaDB to operate on database records - c++

I am trying to use the data records present in my database (MariaDB) by connecting with C++ and using mysql_query to executeSQL query in C++, my goal is to use the data present in the database to my C++ code and perform operations and again push the operated data which is stored in the variable back to the database.
I am facing the problem of
Segmentation error
Query out of sync
I think this is happening because I am using a loop to take the data from the database and then update the records back to the database, and while updating the records I can update static data but I am not able to update the variable data which stores the operating values.
con = mysql_connection_setup(mysqlD); // connection using database id
resultRecord = mysql_execute_query(con, "SELECT Date FROM tableData LIMIT 1000;");
//take data from database into C++ code
cout << "Displaying 10 Database Records: \n"
for (int i = 0; i < 10; i++) // operation on first 10 values
{
databaseTable = mysql_fetch_row(resultRecord); // Fetch the particular data from database
char *DatePtr[i] = {databaseTable[0]}; // Date Column
string dateString = *DatePtr; // function uses string
cout << "Operated Date: ";
DateOperator(dateString); // Function for date operation which returns the operated date.
updateRecord = mysql_execute_query(con, "UPDATE tableData SET DataAge = (#variable value) WHERE Id < 0 ");
}
mysql_free_result(resultRecord); //Free Up the Query
mysql_close(con);
This is my first question on Stack Overflow so please let me know if any update is required in the question. Please help me out of this problem.
Thank you for your time and response.

Related

How do I get the value in MySQL X Dev C++ API from column?

I'm using the MySQL X Dev C++ API (Not the legacy C++ connector) and I want to find the value from a row.
What I have done here is that I create my SQL query command
std::string query = "SELECT * FROM " + std::string(tableName) + " ORDER BY measurement_id DESC LIMIT 1";
Then I execute that command
mysqlx::SqlResult result = connection->sql(query).execute();
Then I check if it has data. If yes, then I fetch one row only. Notice that I can only fetch one row due to the SQL query command only ask for one row.
if (result.hasData()) {
mysqlx::Row row = result.fetchOne();
mysqlx::Value value = row.get(0); // 0 = First column in the row
}
But here is the problem. How can I get this value to the long data type?
mysqlx::Value value = row.get(0);

Retrieving and using last inserted row ID in sqlite

I am aware how to retrieve the last inserted row id in sqlite (by LAST_INSERT_ROWID()).
Assume there is a business logic class Customer with a string name and an int id field.
Consider this piece of pseudo code/MWE:
Customer newCust = Customer();
newCust.setName("Mr. Happy");
createNewCustomer(newCust);
print(newCust.id); // would print "3"
void createNewCustomer(Customer& cust) {
insertNewCustomer(cust.name); // [pseudo code] inserts a new row in DB; id automatically assigned
int id = sqlite3::LAST_INSERT_ROWID(); // [pseudo code] retrieve last inserted row id
cust.id = id;
return;
}
The Customer object is passed by reference, so that its id field can be updated after the query and used in the rest of the program.
Should I wrap the two steps (inserting and retrieving the last id) in a transaction in order to guarantee the last retrieved id is really the one from the query before (think about a scenario with multiple connections accessing in WAL mode for instance).
Is this even a sophisticated approach?

Is it possible to query all records in Cassandra based on a condition?

I have a table with contains a list of user records. I need to query all records based on some condition. The use case is I have about 30 million records in the user table and my condition would match 3 million.
I have gone thru https://www.datastax.com/dev/blog/a-deep-look-to-the-cql-where-clause however, I couldn't find any real solution.
Is it even possible to query Cassandra table based on a condition?
I need to query and paginate the records just like a tradional rdbms or document store.
Cassandra has a concept of paging where you can specify the fetch size and then iterate over it page by page. The below code is if you are using Datastax Java Driver to query data. But other language should also have something similar.
final int RESULTS_PER_PAGE = 100;
Statement st = new SimpleStatement("your query");
st.setFetchSize(RESULTS_PER_PAGE);
String requestedPage = extractPagingStateStringFromURL();
// This will be absent for the first page
if (requestedPage != null) {
st.setPagingState(
PagingState.fromString(requestedPage));
}
ResultSet rs = session.execute(st);
PagingState nextPage = rs.getExecutionInfo().getPagingState();
// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might
// have not respected it, or we might be at the end of the result set
int remaining = rs.getAvailableWithoutFetching();
for (Row row : rs) {
renderInResponse(row);
if (--remaining == 0) {
break;
}
}
// This will be null if there are no more pages
if (nextPage != null) {
renderNextPageLink(nextPage.toString());
}
More details can be found here.

DynamoDB : Get from the last N Records filtered by partition key

I'm new on dynamoDB. I want get latest N records from table.
My table, ChatData has roomNo as partition key and seq as sort key.
Table ChatData stores chat messages.
roomNo is chat room's number. It is not unique.
seq is a sequential number, for giving unique value each message
Then, I want to get latest message specific roomNo.
For example, 20 chat rooms exists(1 form 20). And 100 messages allover rooms(seq from 1 to 100).
In this case how can I get latest 10 messages related 4th chat rooom using JAVA SDK?
I solved.
I used QueryMapper and queryPage method.
Maybe there are many people stucked into similar question, so I upload my code snippets.
ChatDataDemo demo = new ChatDataDemo();
demo.setRoomNo(roomNo);
DynamoDBQueryExpression<ChatDataDemo> queryExpression = new DynamoDBQueryExpression<ChatDataDemo>()
.withLimit(limit).withHashKeyValues(demo).withScanIndexForward(false);
QueryResultPage<ChatDataDemo> items = mapper.queryPage(ChatDataDemo.class,
queryExpression);
for (int i = 0; i < items.getResults().size(); i++) {
ChatDataDemo d = items.getResults().get(i);
System.out.println(d.getSeq() +" / " +d.getMessage());
}
//Maybe need to reverse itemResults using Collection.reverse in next

Qt/SQL - Get column type and name from table without record

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.