我想为我的客户端服务器程序编写SQLite数据库。在数据库中,服务器应该保存来自客户端的每条消息。该表有3列:客户端IP,日期和消息。我编写了以下代码,但在insertmessage()的debbugging期间,我收到此错误:“QSqlError(”“,”“,”“)”。 有什么问题?我应该有一些代码用于连接服务器收到的消息或客户端IP与DB吗?非常感谢。
bool MainWindow::createConnection()
{
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("Message.dat");
if(!database.open())
{
qDebug()<<"can not open database";
database.lastError().text();
return false;
}
return true;
}
MainWindow::messagewindow()
{
enum {
messages_id = 0 ,
messages_date =1 ,
messages_HostAddreess = 2,
messages_message = 3,
};
model = new QSqlTableModel(this);
{
model->setTable("messages");
model->setHeaderData(messages_date, Qt::Horizontal, tr("Date"));
model->setHeaderData(messages_HostAddreess, Qt::Horizontal, tr("From"));
model->setHeaderData(messages_message, Qt::Horizontal, tr("Message"));
model->select();
}
view = new QTableView;
{
view->setSelectionMode(QAbstractItemView::SingleSelection);
view->setSelectionBehavior(QAbstractItemView::SelectRows);
view->setColumnHidden(messages_id, true);
view->setModel(model);
view->resizeColumnsToContents();
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
QHeaderView *header = view->horizontalHeader();
header->setStretchLastSection(true);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
QString HostAddrress;
QDate currentDate;
QString message;
bool create =QFile::exists("Message.dat");
if (!myserver.createConnection())
return 1;
if (create)
myserver.createdata();
myserver.insertMessage( HostAddrress, currentDate, message);
myserver.show();
return a.exec();
}
void MainWindow::createdata()
{
QSqlQuery query;
query.exec("DROP TABLE messages");
query.exec("CREATE TABLE messages("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"HostAddress varchar(20),"
"date varchar(10),"
"message varchar(30))");
}
void MainWindow::insertMessage(QString HostAddrress, QDate currentDate, QString message)
{
QSqlQuery query;
query.prepare("INSERT INTO messages(HostAddress, date, message) values(?,?,?)");
query.addBindValue(HostAddrress);
query.addBindValue(currentDate);
query.addBindValue(message);
query.exec();
if (query.exec()) {
// got no error, proceed
qDebug() << "yes!";
} else {
// got an error, deal with it
qDebug() << query.executedQuery();
qDebug() << query.lastError();
}
}
答案 0 :(得分:0)
您不需要将make database作为类成员,如上所述。 但是当你创建QSqlQuery时,你应该在构造函数中设置数据库,就像这样
QSqlQuery query(QSqlDatabase::database());