QT在使用sql语句时常用QSqlQuery query(m_db)通过通配符和sql语句的方法来实现
1、通配符的方法一:
QSqlQuery query(m_db);
query.prepare( "SELECT * from function_sheilding WHERE sheildType = :type" );
QString str = "TOF";
query.bindValue(":type", str);
if ( !query.exec() ) {
qDebug() << Q_FUNC_INFO << query.lastError().text() << query.lastQuery();
}
int index = 0;
if( query.next() ) {
index = query.value("isSheild").toInt();
}
2、通配符的方法二:
QSqlQuery query(m_db);
query.prepare( "SELECT * from function_sheilding WHERE sheildType = ?" );
QString str = "TOF";
query.bindValue(0, str);
if ( !query.exec() ) {
qDebug() << Q_FUNC_INFO << query.lastError().text() << query.lastQuery();
}
int index = 0;
if( query.next() ) {
index = query.value("isSheild").toInt();
}
3、sql语句exec()方法:
QString sql = QStringLiteral("SELECT * from well_pos");
QSqlQuery query(m_db);
if ( !query.exec(sql) ) {
qDebug() << Q_FUNC_INFO << query.lastError().text();
return false;
}
while( query.next() ) {
QSqlRecord record = query.record();
int well_x = record.value("well_x").toInt();
float tip_h = record.value("tip_h").toFloat();
}
错误的用法(本人自己写的问题):混淆了通配符和标准sql语句的用法
QSqlQuery query(m_db);
QString sql = ( "SELECT * from function_sheilding WHERE sheildType = :type" );
QString str = "TOF";
query.bindValue(":type", str);
if ( !query.exec(sql ) ) {
qDebug() << Q_FUNC_INFO << query.lastError().text() << query.lastQuery();
}
int index = 0;
if( query.next() ) {
index = query.value("isSheild").toInt();
}