I use QSqlDatabase
to insert data to mysql.
First, I define a class named Inserter
:
class Inserter
{
QSqlDatabase db_connection;
public:
Insert()
{
db_connection = QSqlDatabase::addDatabase("QMYSQL");
db_connection.setDatabaseName("dbname");
db_connection.setHostName("localhost");
db_connection.setUserName("root");
db_connection.setPassword("psd");
if(!db_connection.open())
{
qDebug() << db_connection.lastError();
}
}
};
And then, I use Insert
in another class defined as Scheduler:
class Scheduler
{
Inserter inserter;
public:
Scheduler()
{
inserter = Inserter();
}
};
When I run this program, Qt print warning:
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlDatabase::addDatabase() is supposed to be called once per type and connection name. Calling addDatabase("QMYSQL") multiple times leads to
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
Furthermore, having existing QSqlQuery objects while removing a database leads to
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
If the above reason of the warning is right, why the sequence of the warning is not to be:
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
At last, I move the initial code to the class Scheduler
as follow:
class Scheduler
{
QSqlDatabase db_connection;
void initDBConnection()
{
db_connection = QSqlDatabase::addDatabase("QMYSQL");
db_connection.setDatabaseName("walmart");
db_connection.setHostName("localhost");
db_connection.setUserName("root");
db_connection.setPassword("");
if(!db_connection.open())
{
qDebug() << db_connection.lastError();
}
}
public:
Scheduler()
{
initDBConnection();
}
};
There is no warning or errors printed.