• 11289阅读
  • 2回复

[提问]完美解决SQLite读写_控制台输出_界面显示中文问题 [复制链接]

上一主题 下一主题
离线lwtrante
 

只看楼主 倒序阅读 楼主  发表于: 2006-07-01
完美解决SQLite读写_控制台输出_界面显示中文问题
— 本帖被 XChinux 从 Qt基础编程 移动到本区(2013-04-01) —
我的环境是Qt 4.1,直接使用QString的话,无论界面还是数据库读写都是乱码,终于在网路上面搜索到了解决方法,并编写了例子,可能不完善,大家一起研究吧。源码如下:

#include <QtGui/QApplication>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <QtDebug>

#include <QString>
#include <QTextCodec>
#include <QListWidget>
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
 
  QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
 
 
  db.setDatabaseName("e:\\db.db");
      if (!db.open()) {
    QMessageBox::critical(0, qApp->tr("Cannot open database"),
        qApp->tr("Unable to establish a database connection.\n"
              "This example needs SQLite support. Please read "
              "the Qt SQL driver documentation for information how "
              "to build it.\n\n"
              "Click Cancel to exit."), QMessageBox::Cancel,
              QMessageBox::NoButton);
    return false;
  }
 
  QSqlQuery rs(db);

 


 
  rs.exec("create table person(name text,age integer)");
  rs.exec("delete from person where age=119");
  QString strSql("insert into person(name,age) values('中国是在亚洲',119)");
 
 
  rs.exec(strSql);
  bool blnOpen=rs.exec("select * from person");
  if (blnOpen==false)
  {
    qDebug("Query database error\n");
    return -1;
  }
 
  QListWidget *window=new QListWidget();
     
    while (rs.next()) {
          int age= rs.value(1).toInt();
          QString name=rs.value(0).toString();
          window->addItem(name);  
        }
    QString test="这是测试窗体";
    qDebug("字符串的长度是:%d",test.length());
      window->setWindowTitle(test);      
      window->show();
     
  return a.exec();
}
[ 此贴被XChinux在2006-07-02 20:41重新编辑 ]
附件: main.rar (1 K) 下载次数:94
离线woshidag
只看该作者 1楼 发表于: 2010-04-03
好,学习了。
离线gink_chen
只看该作者 2楼 发表于: 2011-05-24
好,学习了。
快速回复
限100 字节
 
上一个 下一个