PDA

View Full Version : QSqlQuery can "insert" data to mssql 2005 enterprise, but can not "select".



csoapy
2nd April 2010, 14:02
QSqlQuery query = QSqlQuery(db);

bool result = query.exec("SELECT Rno FROM tbl_phone WHERE Tel=\'158123456\'");

bool active = query.isActive();
bool sel = query.isSelect();
bool valid = query.isValid();

int rno = query.value(0).toInt();
the rno should be 3. but it is zero always. the active, sel, valid are all false, while result is true.

when debugging, i find an error in QSqlResult:
" [Microsoft][ODBC SQL Server Driver][SQL Server]对象名 'tbl_phone' 无效。 [Microsoft][ODBC SQL Server Driver][SQL Server]该游标未声明。"

[Microsoft][ODBC SQL Server Driver][SQL Server] invalid object name of "tbl_phone", .... this occur is not decleared.

thx.

ajg85
7th April 2010, 22:46
Most likely the database pointed to within your DSN that you connected to with the QSqlDatabase object db for your QSqlQuery does not contain a table by the name of tbl_phone judging by your sql error.

However once that is resolved you will also want to advance your query record position to a valid record before retrieving the result with value() method.



QVariant QSqlQuery::value ( int index ) const
Returns the value of field index in the current record.

The fields are numbered from left to right using the text of the SELECT statement, e.g. in

SELECT forename, surname FROM people;
field 0 is forename and field 1 is surname. Using SELECT * is not recommended because the order of the fields in the query is undefined.

An invalid QVariant is returned if field index does not exist, if the query is inactive, or if the query is positioned on an invalid record.

See also previous(), next(), first(), last(), seek(), isActive(), and isValid().


Example:


QSqlQuery query(db);
if (query.exec("SELECT Rno FROM tbl_phone WHERE Tel=158123456"))
{
query.first(); // or query.next() etc
rno = query.value(0).toInt();
}