How can i print data from table in cpp using sqlite3 db? - c++

I have created a student table in .cpp.
static const char student[] = R"sql(
CREATE TABLE if not exists student(
id VARCHAR(44) NOT NULL,
name varchar NOT NULL,
);
)sql";
I am adding some data in this table from another class. I know data has been added to this table, but I want to print all value from this table for verification.
then I write this statement,
static const char print_student[]="select * from student";
how can I print student table' data in CPP? I am using sqlite3 db.

Related

Does QT have reflections for C++?

I want to create a SQL table in QT C++. So I have made this code.
And it is going to create a database for me, where the first argument tableName is the name of the table I want to create. Then the next argument is quite tricky.
Here, columns, specify the column name and it's data type. I think this is a bad way to do. Example
QVector<QPair<QString, QString>> myColumns = new QVector<QPair<QString, QString>>{{"ID", "BIGINT"}, {"logging_id", "INT"}};
Because If i have for example like 50 columns. The myColumns is going to be very long.
My question if QT C++ have some kind of reflections, so I can:
Get the name if every field
Get the data type of every field
If the field is an array, then I'm going to know how many elements there are inside that array
I was planning to have an entity class where I create a class, and use that class to get the information to create each columns in the database.
void Database::createTable(QString tableName, const QVector<QPair<QString, QString>> columns){
QSqlQuery query;
for (int i = 0; i < columns.length(); i++){
/* Get the Qpair values */
QString columnName = columns.at(i).first;
QString dataType = columns.at(i).second;
/* If key is ID, then try to create a new table */
if(columnName == "ID"){
query.exec("CREATE TABLE " + tableName + "(" + columnName + " " + dataType + " NOT NULL AUTO_INCREMENT PRIMARY KEY)");
continue;
}
/* If not, then try append new columns */
query.exec("ALTER TABLE " + tableName + " ADD " + columnName + " " + dataType);
}
}

Dynamic creation of a table in SQLite3

In the following way, I am creating a table :
rc = sqlite3_exec(db, "create table demo (name text, age integer);", NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
printf("Error: %s:Unable to create the table\n", zErrMsg);
}
Output:
Table: name age
I want to create a table dynamically with the different names & age:
Example:
Table: John 20
Is it possible to create it dynamically?
Requirement :
We want to create a table with column name that can be changed dynamically i.e
from our application we will get a name and we want to create a column in my table with that name.
We are facing data type conflict.
Example :
From our application we will get a character array :
char a[5] = "John".
We need to create a column with John as column name.
Thanks in advance

How i can save the char data directly to blob db?

I need to save an wxBitmap to SQLite to a blob type without save to disk or on some media.
i have mybitmap as wxBitmap;
First must convert to wxImage and get data.
Ok until now i hope, but how i can save the char data directly to blob db?
In sql must have
update mytable SET blob_column='??????' WHERE id='1'
or something like that. How must construct query?
wxImage img=mybitmap.ConvertToImage();
unsigned char* data=img.GetData();
int datalength=img.GetWidth()*img.GetHeight()*3;
char *myBuffer = (char *)data;
The code bellow is for wxSQLite3 ...
wxMemoryOutputStream mo;
img.SaveFile( mo, wxBITMAP_TYPE_PNG );
wxSQLite3Statement stmt = db.PrepareStatement("UPDATE mytable SET blob_column='?' WHERE id='1'");
stmt.Bind(0, (unsigned char *)mo.GetOutputStreamBuffer()->GetBufferStart(), mo.GetOutputStreamBuffer()->GetBufferSize());
stmt.ExecuteUpdate();
But how to translate for SQLite?

Trying to modify an sqlite3 insert to return the PK. Wasn't sure how to do it with sqlite3 specifically

I was trying to insert into a table some data, but I wasn't sure what flag allows me to return the primary key. I believe I recall MSSQL using RETURNING, and some others tack on RETURNS at the end.
could someone help out with the appending of it?
I'm trying to return TABLEA.a, and my query and design would look something like this:
sqlite3 *db;
sqlite3_open("...",&db);
std::string query;
query = "insert into TABLEA (b,c,d,e) values (#b,\"#c\",#d,#e);";
//^--this needs to be modified.
sqlite3_stmt *sqlstmt;
int rc;
rc = sqlite3_prepare_v2(db, query.c_str(), 01, &sqlstmt, 0);
sqlite3_step(sqlstmt);
int ID;
ID = sqlite3_column_integer(sqlstmt,0);
Have you tried sqlite3_last_insert_rowid ?

Testing NHibernate with SQLite "No Such Table" - schema is generated

I'm trying to use an in-memory SQLite database to test my data layer which is provided by NHibernate.
I've read a load of blogs and articles about getting this setup but I'm now very confused as to why it isn't working.
The problem - when I run a unit test I get the error 'no such table: Student'. The articles I've read suggest this is because the schema isn't getting generated, or, the connection is being closed between my SchemaExport and query. I've checked everywhere I can think of and can't see how either of these scenarios are occuring.
My test output log looks like this:
OPEN CONNECTION
drop table if exists "Student"
drop table if exists "Tutor"
create table "Student" (
ID integer,
Name TEXT,
DoB DATETIME,
TutorId INTEGER,
primary key (ID)
)
create table "Tutor" (
ID integer,
Name TEXT,
primary key (ID)
)
NHibernate: INSERT INTO "Student" (Name, DoB, TutorId) VALUES (#p0, #p1, #p2); select last_insert_rowid();#p0 = 'Text1', #p1 = 01/12/2010 14:55:05, #p2 = NULL
14:55:05,750 ERROR [TestRunnerThread] AbstractBatcher [(null)]- Could not execute query: INSERT INTO "Student" (Name, DoB, TutorId) VALUES (#p0, #p1, #p2); select last_insert_rowid()
System.Data.SQLite.SQLiteException (0x80004005): SQLite error
no such table: Student
at System.Data.SQLite.SQLite3.Prepare(String strSql, SQLiteStatement previous, String& strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
14:55:05,781 ERROR [TestRunnerThread] ADOExceptionReporter [(null)]- SQLite error
no such table: Student
DISPOSE
CLOSING CONNECTION
Originally I was using my own code for the connection/session management but have moved to the code in this blog post translated to C# and with a couple changes to the DBConfig method and some debug statements to show the state of the connection.
private FluentNHibernate.Cfg.Db.IPersistenceConfigurer GetDBConfig()
{
return SQLiteConfiguration.Standard
.ConnectionString((ConnectionStringBuilder cs) => cs.Is(CONNECTION_STRING))
.ProxyFactoryFactory("NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
.Raw("connection.release_mode", "on_close");
}
I added the on_close after reading this
My test code looks like this:
[Test]
public void CanGetStudentById()
{
using (var scope = new SQLiteDatabaseScope<StudentMapping>())
{
using (ISession sess = scope.OpenSession())
{
// Arrange
var repo = new StudentRepository();
repo.Save(new Student() { Name = "Text1", DoB = DateTime.Now });
// Act
var student = repo.GetById(1);
// Assert
Assert.IsNotNull(student);
Assert.AreEqual("Text1", student.Name);
}
}
}
What have I overlooked here?
Update: I created a copy of the class that connects to an SQLite file DB and it worked fine. So it has to be something to do with the connection being closed.
If you change your test method to the following, does it work?
[Test]
public void CanGetStudentById()
{
using (var scope = new SQLiteDatabaseScope<StudentMapping>())
{
using (ISession sess = scope.OpenSession())
{
// Arrange
sess.Save(new Student() { Name = "Text1", DoB = DateTime.Now });
// Act
var student = sess.Get<Student>(1);
// Assert
Assert.IsNotNull(student);
Assert.AreEqual("Text1", student.Name);
}
}
}
I would hazard to guess that your StudentRepository is opening its own session and hence doesn't see the table.