我在 MS SQL 服务器中有一个数据库,我的问题是 unicode 字符!我的“getRecordByCondition”方法中的“query.exec(str)”返回“?” char 用于 nvarchar 字段!但它在“loadToGrid”方法中正确工作。这是我的代码:
void DataAccess::connect()
{
db=QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("TestDB");
}
void DataAccess::disConnect()
{
QString connection;
connection = db.connectionName();
db.close();
}
QVariantList DataAccess::getRecordByCondition(QString tableName, QString condition)
{
connect();
QVariantList recordData;
QString str= " select * from " + tableName + " where " + condition ;
QSqlRecord record;
QSqlQuery query(db);
if(db.open())
{
// can run
if(query.exec(str))
{
record=query.record();
int cols=record.count();
while (query.next())
{
for(int i=0;i<cols;i++)
{
qDebug() << query.value(i); // ??????? ????
recordData << query.value(i);
}
}
disConnect();
//return 1;
}
else
{
qDebug() << "problem!" << db.lastError();
disConnect();
//return -1;
}
}
else
{
qDebug() << "db can not open because:" << db.lastError().text();
//return -2;
}
disConnect();
return recordData;
}
void DataAccess::loadToGrid(QString tableName, QTableView &grid)
{
connect();
if(db.open())
{
//Load data
QString qry="select * from " + tableName;
QSqlRecord record;
QSqlQuery query(db);
if(query.exec(qry))
{
record=query.record();
int cols=record.count();
int rows=0;
//make model
QStandardItemModel *myModel=new QStandardItemModel(0,cols,grid.parent());
//make headers
for(int i=0;i<cols;i++)
{
myModel->setHorizontalHeaderItem(i,new QStandardItem(record.fieldName(i)));
}
while (query.next()) {
for(int i=0;i<cols;i++)
{
myModel->setItem(rows,i,new QStandardItem(query.value(i).toString()));
}
rows++;
}
grid.setModel(myModel);
}
}
disConnect();
}