gpt4 book ai didi

Qt - QSql 无法获取行,尝试插入时没有查询

转载 作者:IT王子 更新时间:2023-10-29 06:32:25 34 4
gpt4 key购买 nike

我正在尝试将数据插入表中。这是代码:

void AddContacts::saveContact() {

QString first_name = ui->lineFirstName->text();
QString last_name = ui->lineLastName->text();
QString street_address = ui->lineStreetAddress->text();
QString city = ui->lineCity->text();
QString state = ui->comboBoxState->currentText();
QString zip_code = ui->lineZip->text();
QString personal_email = ui->linePersonalEmail->text();
QString work_email = ui->lineWorkEmail->text();
QString home_phone = ui->lineHomePhone->text();
QString cellular_phone = ui->lineCellularPhone->text();
QString work_phone = ui->lineWorkPhone->text();
QString pager = ui->linePager->text();
QString facebook = ui->lineFacebook->text();
QString twitter = ui->lineTwitter->text();
QString notes = ui->textEditNotes->toPlainText();

// Insert into the database
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("db.db3");
db.open();

QSqlQuery qry;
QString query = "INSERT INTO (id, first_name, last_name, street_address, city, state, zip_code, personal_email, work_email, home_phone, cellular_phone, work_phone, pager, facebook, twitter, notes) VALUES('null','" + first_name + "','" + last_name +"','" + street_address + "','" + city + "','" + state + "','" + zip_code + "','" + personal_email + "','" + work_email + "','" + home_phone + "','" + cellular_phone + "','" + work_phone + "','" + pager + "','" + facebook + "','" + twitter + "', '" + notes + "')";
qry.prepare(query);

if(!qry.exec()) {
qDebug() << qry.lastError();
}
else {
qDebug() << "Success!";
}

这是我用来创建表格的内容:

CREATE TABLE contacts (
id int primary key,
first_name varchar(20),
last_name varchar(20),
street_address text,
city varchar(30),
state varchar(20),
zip_code varchar(10),
personal_email varchar(40),
work_email varchar(40),
home_phone varchar(12),
cellular_phone varchar(12),
work_phone varchar(12),
pager varchar(12),
facebook text,
twitter varchar(20),
notes text);

我收到这个错误:

QSqlError(-1, "Unable to fetch row", "No query")

我不确定自己做错了什么。你能找到什么吗?

最佳答案

不要插入字符串 'null' 作为列 id 的值。请改用有效整数。如果您真的希望第一行有一个 NULL id,SQL 语句看起来像这样 ... VALUES (NULL, ...

您的代码很容易出错,因为您没有在输入中转义撇号。如果您的某些文本字段包含 ',您的 SQL 语句将失败。您应该将列绑定(bind)到变量。这是来自 Qt 引用,你应该使用这种方法:

 QSqlQuery query;
query.prepare("INSERT INTO contacts (id, first_name, last_name) "
"VALUES (:id, :first_name, :last_name)");
query.bindValue(":id", 1001);
query.bindValue(":first_name", first_name);
query.bindValue(":last_name", last_name);
query.exec();

关于Qt - QSql 无法获取行,尝试插入时没有查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6891249/

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