现在我正在研究Qt项目,我需要一些MySQL支持。 MySQL安装在Ubuntu Server上的虚拟机(Virtual Box)上。这是我的所作所为:
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QSqlDatabase hospital_db = QSqlDatabase::addDatabase("QMYSQL");
hospital_db.setHostName("192.168.56.10");
hospital_db.setDatabaseName("hospital_db");
hospital_db.setUserName("usr1");
hospital_db.setPassword("123");
if(!hospital_db.open()) {
qDebug() << "\nFailed connect to MySQL";
};
QTableView *tView = new QTableView;
QSqlTableModel model;
model.setTable("my_table");
model.setEditStrategy(QSqlTableModel::OnManualSubmit);
if (!model.select()) {
QMessageBox msgBox;
QString err(model.lastError().text());
msgBox.setText(err);
msgBox.exec();
}
model.setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model.setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
model.setHeaderData(2, Qt::Horizontal, QObject::tr("Address"));
model.setHeaderData(3, Qt::Horizontal, QObject::tr("Phone"));
tView->setModel(&model);
tView->show();
QSqlDatabase::removeDatabase("my_table");
return app.exec();
}
我收到“无法找到表my_table”错误。表my_table已正确创建。这是SHOW FIELDS OF my_table
:
+----------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-----------+------+-----+---------+----------------+
| hosp_id | int(11) | NO | PRI | NULL | auto_increment |
| hosp_name | char(100) | NO | | NULL | |
| hosp_address | char(100) | NO | | NULL | |
| hosp_ph_number | char(8) | NO | | NULL | |
+----------------+-----------+------+-----+---------+----------------+
最后来自MySQL的general_log:
| 2011-08-11 12:21:54 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Connect | usr1@192.168.56.1 on hospital_db |
| 2011-08-11 12:21:54 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Init DB | hospital_db |
| 2011-08-11 12:21:54 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Query | SET NAMES utf8 |
| 2011-08-11 12:21:54 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Field List | my_table |
| 2011-08-11 12:21:54 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Field List | my_table |
| 2011-08-11 12:21:54 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Query | show index from my_table |
| 2011-08-11 12:22:01 | usr1[usr1] @ [192.168.56.1] | 36 | 0 | Quit | |
那么,我做错了什么?
答案 0 :(得分:0)
你在做什么
model.setTable("mytable");
但是根据你的SQL,表名是“my_table”。他们是不同的!
答案 1 :(得分:0)
好吧,似乎我在服务器端的权限有些问题。现在一切都很好。