gpt4 book ai didi

c++ - QSqlError ("", "", "")

转载 作者:太空宇宙 更新时间:2023-11-04 13:22:36 24 4
gpt4 key购买 nike

我想为我的客户端服务器程序编写 SQLite 数据库。在数据库中,服务器应该保存来自客户端的每条消息。该表有 3 列:客户端 IP、日期和消息。我编写了以下代码,但在 insertmessage() 调试期间出现此错误:“QSqlError(”, “”, “”) ”。它有什么问题?我应该有一些代码来连接服务器收到的消息或客户端 IP 与数据库吗?非常感谢。

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();
}
}

最佳答案

你不需要像上面评论的那样让数据库成为类成员。但是当你创建你的 QSqlQuery 时,你应该像这样在构造函数中设置数据库

QSqlQuery query(QSqlDatabase::database());

关于c++ - QSqlError ("", "", ""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com