When i push the Button, it views this error : QSqlQuery::exec: database not open
当我按下按钮时,它会查看这个错误:QSqlQuery: exec: database not open
void Tester::pushButtonClicked()
{
if (database.open() )
{
model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable");
model->setHeaderData(0, Qt::Horizontal, tr("ID"));
model->setHeaderData(1, Qt::Horizontal, tr("Nachnamme"));
model->setHeaderData(2, Qt::Horizontal, tr("Vorname"));
model->setHeaderData(3, Qt::Horizontal, tr("Ort"));
} else
{
qDebug("Nicht geöffnet");
}
meineView->setModel(model);
}
whats wrong ? database is a QSqlDatabase . model is a QSqlQueryModel. I have connect it so :
什么错了吗?数据库是一个QSqlDatabase。模型是QSqlQueryModel。我把它连接起来:
database = QSqlDatabase::addDatabase("QMYSQL", "conn1");
//database->addDatabase("QMYSQL", "conn1");
database.setHostName("127.0.0.1");
database.setPort(3306);
database.setDatabaseName( "mydb" );
database.setUserName("root");
database.setPassword("XXXX");
if ( !database.open() )
{
qDebug("Couldn't open DB");
}
2 个解决方案
#1
1
What is the error you are facing ? Use QSqlDatabase::lastError() to retrieve the error, if any, on opening the connection.
你所面临的错误是什么?使用QSqlDatabase::lastError()检索打开连接时的错误(如果有的话)。
Also I think you are trying to open the database twice. Once when you create the database object and other in the button click. Check that database is already open using the isOpen() method on button click.
而且我认为您正在尝试两次打开数据库。当您在按钮单击时创建数据库对象和其他对象时。在单击按钮时使用isOpen()方法检查数据库是否已经打开。
#2
1
I have the answer ! I have forget to set the database fot the Query. It must look like : model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable", database);
我知道答案了!我忘记设置查询的数据库。它必须看起来像:model->setQuery(“选择id、Nachname、Vorname、Ort FROM testtable”、数据库);
#1
1
What is the error you are facing ? Use QSqlDatabase::lastError() to retrieve the error, if any, on opening the connection.
你所面临的错误是什么?使用QSqlDatabase::lastError()检索打开连接时的错误(如果有的话)。
Also I think you are trying to open the database twice. Once when you create the database object and other in the button click. Check that database is already open using the isOpen() method on button click.
而且我认为您正在尝试两次打开数据库。当您在按钮单击时创建数据库对象和其他对象时。在单击按钮时使用isOpen()方法检查数据库是否已经打开。
#2
1
I have the answer ! I have forget to set the database fot the Query. It must look like : model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable", database);
我知道答案了!我忘记设置查询的数据库。它必须看起来像:model->setQuery(“选择id、Nachname、Vorname、Ort FROM testtable”、数据库);