Connecting Mysql and qt?
I'm having some difficulties connecting a program I'm building with qt. And once I do that, how do I get the database to work with a table widget?
I should probably let you know that I开发者_开发百科 don't know where to begin other than I made the database with libreoffice base.
Qt provides the model/view framework which is a very flexible tool for presenting data in tables, trees, or lists. so the model you need to use is QSqlTableModel
.
First create a QSqlDatabase instance, and connect to the database
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("my_database");
db.setUserName("username");
db.setPassword("password");
if(!db.open())
QMessageBox::warning(this,"Error","Unable to connect to the database");
then create the model
QSqlTableModel *model = new QSqlTableModel(parent,db);
model->setTable("students");
model->select(); //< fetch data
and finally tell the table to diplay data from this model
QTableView *table = new QTableView;
table->setModel(model);
Under Qt's help system, take a look at Examples, go to SQL, and pick the Table Model Example. You'll find it's not that hard to use MySQL with Qt. (You may have to hand-compile the qtmysql driver; on my system it's in /QtSources/4.7.3/src/plugins/sqldrivers/mysql/mysql.pro. Just qmake/make/make install. Good luck and enjoy!
- add QT +=Core sql into .pro
- download libmysq.dll and add to Qt-> Qt 5.3.0 -> mingw482_32 -> Plugins -> sqldrivers
- create new Qt console file
- add this line to main.cpp
.
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("");
db.setDatabaseName("sim");
if(db.open())
{
qDebug() << "connected " << db.hostName();
}else{
qDebug() << "Connection FAILED.";
}
return a.exec();
}
精彩评论