I have two classes I need to use an instance variable of the class QSqlDatabase to set database connections. I created an instance variable of the QSqlDatabase class in both classes under private:
--------------- Header file----------------
//Data struct for user event log
struct userEventLogMsg{
//hold all values for a single list entry,
};
//---Class UserEventDailyLog responsible for XMUI UserEvnetLog | Subed classed: QAbstractTableModel---//
{
Q_OBJECT
public:
explicit UserEventLog
(QObject *parent
= 0);
~UserEventLog();
enum userEventRoles {idRole= Qt::UserRole + 220, nameRole, msgRole, dateRole};
QHash<int, QByteArray> roleNames() const;
Q_INVOKABLE void addEvent(const userEventLogMsg &msg);
void dbConnect();
void sqlSelect();
private:
QList<userEventLogMsg> m_userEventList;
};
//Data struct for user event log
struct userEventLogMsg{
//hold all values for a single list entry,
QString id;
QString username;
QString eventmessage;
QString datetime;
};
//---Class UserEventDailyLog responsible for XMUI UserEvnetLog | Subed classed: QAbstractTableModel---//
class UserEventLog : public QAbstractListModel
{
Q_OBJECT
public:
explicit UserEventLog(QObject *parent = 0);
~UserEventLog();
enum userEventRoles {idRole= Qt::UserRole + 220, nameRole, msgRole, dateRole};
int rowCount(const QModelIndex & parent) const;
QHash<int, QByteArray> roleNames() const;
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const;
Q_INVOKABLE void addEvent(const userEventLogMsg &msg);
void dbConnect();
void sqlSelect();
private:
QList<userEventLogMsg> m_userEventList;
QSqlDatabase m_selectDataBase;
};
To copy to clipboard, switch view to plain text mode
//---------CPP file--------------//
//
// UserEventLogModel
//
//---Constructor---//
}
//---Destructor---//
UserEventLog::~UserEventLog() {
}
int UserEventLog
::rowCount(const QModelIndex &parent
) const { Q_UNUSED(parent);
qDebug()<< m_userEventList.count();
return m_userEventList.count();
}
QHash<int, QByteArray> UserEventLog::roleNames() const {
QHash<int, QByteArray> roleNames;
roleNames.insert(idRole, "id");
roleNames.insert(nameRole, "userName");
roleNames.insert(msgRole, "eventMessage");
roleNames.insert(dateRole, "dateTime");
qDebug()<< roleNames;
return roleNames;
}
if (index.row() < 0 || index.row() >= m_userEventList.count()){
}
if(role == idRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.id;
qDebug() << text;
}
else if(role == nameRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.username;
qDebug() << text;
}
else if(role == msgRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.eventmessage;
qDebug() << text;
}
if(role == dateRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.datetime;
qDebug() << text;
}
return text;
}
void UserEventLog::addEvent(const userEventLogMsg &msg) {
m_userEventList.insert(0, msg);
endInsertRows();
}
void UserEventLog::dbConnect() {
m_selectDataBase
= QSqlDatabase::addDatabase("QSQLITE",
"conn2");
qDebug() << m_selectDataBase.isValid();
m_selectDataBase.setDatabaseName("/home/amet/userLog.db");
m_selectDataBase.open();
if(!m_selectDataBase.open()){
qDebug() <<"error in opening DB";
}
else{
qDebug() <<"connected to DB" ;
}
}
void UserEventLog::sqlSelect() {
//m_selectDataBase = QSqlDatabase::database("conn2");
qDebug() << m_selectDataBase.isValid();
m_selectDataBase.open();
selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents");
qDebug() <<selectQuery.lastError();
if(selectQuery.exec()){
qDebug()<<"sql statement exicuted fine";
}
else{
qDebug() <<"Errors accured with sql statement";
qDebug() <<selectQuery.lastError();
}
while (selectQuery.next()){
userEventLogMsg msg;
UserEventLog model;
msg.id = selectQuery.value(0).toString();
msg.username = selectQuery.value(1).toString();
msg.eventmessage = selectQuery.value(2).toString();
msg.datetime = selectQuery.value(3).toString();
model.addEvent(msg);
}
//m_selectDataBase.close();
//m_selectDataBase.removeDatabase("conn2");
}
//----------------------------------------------------------------//
//---------CPP file--------------//
//
// UserEventLogModel
//
//---Constructor---//
UserEventLog::UserEventLog(QObject *parent):QAbstractListModel(parent) {
}
//---Destructor---//
UserEventLog::~UserEventLog() {
}
int UserEventLog::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
qDebug()<< m_userEventList.count();
return m_userEventList.count();
}
QHash<int, QByteArray> UserEventLog::roleNames() const {
QHash<int, QByteArray> roleNames;
roleNames.insert(idRole, "id");
roleNames.insert(nameRole, "userName");
roleNames.insert(msgRole, "eventMessage");
roleNames.insert(dateRole, "dateTime");
qDebug()<< roleNames;
return roleNames;
}
QVariant UserEventLog::data(const QModelIndex &index, int role) const {
if (index.row() < 0 || index.row() >= m_userEventList.count()){
return QVariant();
}
QVariant text;
if(role == idRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.id;
qDebug() << text;
}
else if(role == nameRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.username;
qDebug() << text;
}
else if(role == msgRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.eventmessage;
qDebug() << text;
}
if(role == dateRole) {
userEventLogMsg msg = m_userEventList.at(index.row());
text = msg.datetime;
qDebug() << text;
}
return text;
}
void UserEventLog::addEvent(const userEventLogMsg &msg) {
beginInsertRows(QModelIndex(), 0, 0);
m_userEventList.insert(0, msg);
endInsertRows();
}
void UserEventLog::dbConnect() {
m_selectDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn2");
qDebug() << m_selectDataBase.isValid();
m_selectDataBase.setDatabaseName("/home/amet/userLog.db");
m_selectDataBase.open();
if(!m_selectDataBase.open()){
qDebug() <<"error in opening DB";
}
else{
qDebug() <<"connected to DB" ;
}
}
void UserEventLog::sqlSelect() {
//m_selectDataBase = QSqlDatabase::database("conn2");
qDebug() << m_selectDataBase.isValid();
m_selectDataBase.open();
QSqlQuery selectQuery;
selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents");
qDebug() <<selectQuery.lastError();
if(selectQuery.exec()){
qDebug()<<"sql statement exicuted fine";
}
else{
qDebug() <<"Errors accured with sql statement";
qDebug() <<selectQuery.lastError();
}
while (selectQuery.next()){
userEventLogMsg msg;
UserEventLog model;
msg.id = selectQuery.value(0).toString();
msg.username = selectQuery.value(1).toString();
msg.eventmessage = selectQuery.value(2).toString();
msg.datetime = selectQuery.value(3).toString();
model.addEvent(msg);
}
//m_selectDataBase.close();
//m_selectDataBase.removeDatabase("conn2");
}
//----------------------------------------------------------------//
To copy to clipboard, switch view to plain text mode
my other class that need a database connection to the same database
---------CPP file-----------
void XMUI::hdpiWindow()
{
mUserEventLogModel = new UserEventLog();
mUserEventLogModel->dbConnect();
mUserEventLogModel->sqlSelect();
m_QmlEngine->rootContext()->setContextProperty("UserEventLog", mUserEventLogModel);
}
void XMUI
::insertLogMessage(QString msg
) {
m_insertDataBase
= QSqlDatabase::addDatabase("QSQLITE",
"conn1");
m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
m_insertDataBase.open();
if(m_insertDataBase.isOpen()){
qDebug() <<"connected to DB" ;
}
else{
qDebug() <<"error in opening DB";
m_insertDataBase.open();
}
qDebug() << "insert Log Message called";
insertQuery.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', ':eventMessage', datetime(current_timestamp))");
insertQuery.bindValue(":eventMessage", msg);
insertQuery.exec();
//m_insertDataBase.close();
//m_insertDataBase.removeDatabase("conn1");
}
void XMUI::hdpiWindow()
{
mUserEventLogModel = new UserEventLog();
mUserEventLogModel->dbConnect();
mUserEventLogModel->sqlSelect();
m_QmlEngine->rootContext()->setContextProperty("UserEventLog", mUserEventLogModel);
}
void XMUI::insertLogMessage(QString msg)
{
m_insertDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn1");
m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
m_insertDataBase.open();
if(m_insertDataBase.isOpen()){
qDebug() <<"connected to DB" ;
}
else{
qDebug() <<"error in opening DB";
m_insertDataBase.open();
}
qDebug() << "insert Log Message called";
QSqlQuery insertQuery(m_insertDataBase);
insertQuery.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', ':eventMessage', datetime(current_timestamp))");
insertQuery.bindValue(":eventMessage", msg);
insertQuery.exec();
//m_insertDataBase.close();
//m_insertDataBase.removeDatabase("conn1");
}
To copy to clipboard, switch view to plain text mode
----header file--------
{
Q_OBJECT
public:
explicit XMUI(QQuickWidget* _quickWidget);
void hdpiWindow();
Q_INVOKABLE
void insertLogMessage
(QString msg
);
private:
class XMUI : public QObject
{
Q_OBJECT
public:
explicit XMUI(QQuickWidget* _quickWidget);
void hdpiWindow();
Q_INVOKABLE void insertLogMessage(QString msg);
private:
QSqlDatabase m_insertDataBase;
To copy to clipboard, switch view to plain text mode
Added after 18 minutes:
Originally Posted by
anda_skoa
Yes
You pass the QSqlDatabase handle to the QSqlQuery constructor.
insertQuery.prepare(...);
QSqlQuery insertQuery(m_insertDataBase);
insertQuery.prepare(...);
To copy to clipboard, switch view to plain text mode
I was passing the name of my connection not the instance variable, changed it to instance variable.
if (!m_insertDataBase.isValid() {
// addDatabase, setDatabaseName
}
if (!m_insertDataBase.isValid() {
// addDatabase, setDatabaseName
}
To copy to clipboard, switch view to plain text mode
Cheers,
_
I moved the add and set methods inside an if condition to set them if the database is not valid. However I get confused because I need to connect to the database to begin with... If I'm only setting them when it not valid how do I initially set the connect the first time. set it in the constructor?
void XMUI
::insertLogMessage(QString msg
) {
//qDebug() << m_insertDataBase.connectionNames();
if(!m_insertDataBase.isValid()){
qDebug() <<"error in opening DB";
m_insertDataBase
= QSqlDatabase::addDatabase("QSQLITE",
"conn1");
m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
qDebug() << m_insertDataBase.connectionNames();
}
else{
qDebug() <<"connected to DB";
m_insertDataBase.open();
//qDebug() << m_insertDataBase.lastError();
}
m_insertDataBase.open();
m_insertQuery.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', ':eventMessage', datetime(current_timestamp))");
m_insertQuery.bindValue(":eventMessage", msg);
m_insertQuery.exec();
qDebug() << m_insertQuery.lastError();
//m_insertDataBase.close();
//QSqlDatabase::removeDatabase("conn1");
}
void XMUI::insertLogMessage(QString msg)
{
//qDebug() << m_insertDataBase.connectionNames();
if(!m_insertDataBase.isValid()){
qDebug() <<"error in opening DB";
m_insertDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn1");
m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
qDebug() << m_insertDataBase.connectionNames();
}
else{
qDebug() <<"connected to DB";
m_insertDataBase.open();
//qDebug() << m_insertDataBase.lastError();
}
m_insertDataBase.open();
QSqlQuery m_insertQuery(m_insertDataBase);
m_insertQuery.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', ':eventMessage', datetime(current_timestamp))");
m_insertQuery.bindValue(":eventMessage", msg);
m_insertQuery.exec();
qDebug() << m_insertQuery.lastError();
//m_insertDataBase.close();
//QSqlDatabase::removeDatabase("conn1");
}
To copy to clipboard, switch view to plain text mode
Bookmarks