免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4360 | 回复: 2

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

论坛徽章:
0
发表于 2011-03-22 23:55 |显示全部楼层
我的环境是Qt 4.1,直接使用QString的话,无论界面还是数据库读写都是乱码,终于在网路上面搜索到了解决方法,并编写了例子,可能不完善,大家一起研究吧。源码如下:
  1. #include <QtGui/QApplication>
  2. #include <QMessageBox>
  3. #include <QSqlDatabase>
  4. #include <QSqlError>
  5. #include <QSqlQuery>
  6. #include <QVariant>
  7. #include <QtDebug>

  8. #include <QString>
  9. #include <QTextCodec>
  10. #include <QListWidget>

  11. int main(int argc, char *argv[])
  12. {
  13.   QApplication a(argc, argv);

  14.   QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
  15.   QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");


  16.   db.setDatabaseName("e:\\db.db");
  17.       if (!db.open()) {
  18.     QMessageBox::critical(0, qApp->tr("Cannot open database"),
  19.         qApp->tr("Unable to establish a database connection.\n"
  20.               "This example needs SQLite support. Please read "
  21.               "the Qt SQL driver documentation for information how "
  22.               "to build it.\n\n"
  23.               "Click Cancel to exit."), QMessageBox::Cancel,
  24.               QMessageBox::NoButton);
  25.     return false;
  26.   }

  27.   QSqlQuery rs(db);


  28.   rs.exec("create table person(name text,age integer)");
  29.   rs.exec("delete from person where age=119");
  30.   QString strSql("insert into person(name,age) values('中国是在亚洲',119)");


  31.   rs.exec(strSql);
  32.   bool blnOpen=rs.exec("select * from person");
  33.   if (blnOpen==false)
  34.   {
  35.     qDebug("Query database error\n");
  36.     return -1;
  37.   }

  38.   QListWidget *window=new QListWidget();
  39.      
  40.     while (rs.next()) {
  41.           int age= rs.value(1).toInt();
  42.           QString name=rs.value(0).toString();
  43.           window->addItem(name);  
  44.         }
  45.     QString test="这是测试窗体";
  46.     qDebug("字符串的长度是:%d",test.length());
  47.       window->setWindowTitle(test);      
  48.       window->show();
  49.      
  50.   return a.exec();
  51. }
复制代码

论坛徽章:
1
黑曼巴
日期:2020-02-27 22:54:26
发表于 2011-03-23 14:46 |显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:56:11
发表于 2011-03-24 15:11 |显示全部楼层
我用utf8,都能正常顯示。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP