网络服务器软件开发/中间件开发,关注ACE/ICE/boost

C++博客 首页 新随笔 联系 聚合 管理
  152 Posts :: 3 Stories :: 172 Comments :: 0 Trackbacks

#

MySQL服务维护笔记


内容摘要:使用MySQL服务的一些经验,主要从以下几个方面考虑的MySQL服务规划设计。对于高负载站点来说PHP和MySQL运行在一起(或者说任何应用和数据库运行在一起的规划)都是性能最大的瓶颈,这样的设计有如让人一手画圆一手画方,这样2个人的工作效率肯定不如让一个人专门画圆一个人专门画方效率高,让应用和数据库都跑在一台高性能服务器上说不定还不如跑在2台普通服务器上快。

以下就是针对MySQL作为专门的数据库服务器的优化建议:

  1. MySQL服务的安装/配置的通用性;
  2. 系统的升级和数据迁移方便性;
  3. 备份和系统快速恢复;
  4. 数据库应用的设计要点;
  5. 一次应用优化实战;

MySQL服务器的规划
=================
为了以后维护,升级备份的方便和数据的安全性,最好将MySQL程序文件和数据分别安装在“不同的硬件”上。

         /   / 
| /usr <== 操作系统
| /home/mysql <== mysql主目录,为了方便升级,这只是一个最新版本目录的链接
硬盘1==>| /home/mysql-3.23.54/ <== 最新版本的mysql /home/mysql链接到这里
\ /home/mysql-old/ <== 以前运行的旧版本的mysql

/ /data/app_1/ <== 应用数据和启动脚本等
硬盘2==>| /data/app_2/
\ /data/app_3/

MySQL服务的安装和服务的启动:
MySQL一般使用当前STABLE的版本:
尽量不使用--with-charset=选项,我感觉with-charset只在按字母排序的时候才有用,这些选项会对数据的迁移带来很多麻烦。
尽量不使用innodb,innodb主要用于需要外键,事务等企业级支持,代价是速度比MYISAM有数量级的下降。
./configure --prefix=/home/mysql --without-innodb
make
make install

服务的启动和停止
================
1 复制缺省的mysql/var/mysql到 /data/app_1/目录下,
2 MySQLD的启动脚本:start_mysql.sh
#!/bin/sh
rundir=`dirname "$0"`
echo "$rundir"
/home/mysql/bin/safe_mysqld --user=mysql --pid-file="$rundir"/mysql.pid --datadir="$rundir"/var "$@"\
-O max_connections=500 -O wait_timeout=600 -O key_buffer=32M --port=3402 --socket="$rundir"/mysql.sock &

注释:
--pid-file="$rundir"/mysql.pid --socket="$rundir"/mysql.sock --datadir="$rundir"/var
目的都是将相应数据和应用临时文件放在一起;
-O 后面一般是服务器启动全局变量优化参数,有时候需要根据具体应用调整;
--port: 不同的应用使用PORT参数分布到不同的服务上去,一个服务可以提供的连接数一般是MySQL服务的主要瓶颈;

修改不同的服务到不同的端口后,在rc.local文件中加入:
/data/app_1/start_mysql.sh
/data/app_2/start_mysql.sh
/data/app_3/start_mysql.sh
注意:必须写全路径

3 MySQLD的停止脚本:stop_mysql.sh
#!/bin/sh
rundir=`dirname "$0"`
echo "$rundir"
/home/mysql/bin/mysqladmin -u mysql -S"$rundir"/mysql.sock shutdown

使用这个脚本的好处在于:
1 多个服务启动:对于不同服务只需要修改脚本中的--port[=端口号]参数。单个目录下的数据和服务脚本都是可以独立打包的。
2 所有服务相应文件都位于/data/app_1/目录下:比如:mysql.pid mysql.sock,当一台服务器上启动多个服务时,多个服务不会互相影响。但都放到缺省的/tmp/下则有可能被其他应用误删。
3 当硬盘1出问题以后,直接将硬盘2放到一台装好MySQL的服务器上就可以立刻恢复服务(如果放到my.cnf里则还需要备份相应的配置文件)。

服务启动后/data/app_1/下相应的文件和目录分布如下:
/data/app_1/
    start_mysql.sh 服务启动脚本
    stop_mysql.sh 服务停止脚本
    mysql.pid 服务的进程ID
    mysql.sock 服务的SOCK
    var/ 数据区
       mysql/ 用户库
       app_1_db_1/ 应用库
       app_1_db_2/
...
/data/app_2/
...

查看所有的应用进程ID:
cat /data/*/mysql.pid

查看所有数据库的错误日志:
cat /data/*/var/*.err

个人建议:MySQL的主要瓶颈在PORT的连接数上,因此,将表结构优化好以后,相应单个MySQL服务的CPU占用仍然在10%以上,就要考虑将服务拆分到多个PORT上运行了。

服务的备份
==========
尽量使用MySQL DUMP而不是直接备份数据文件,以下是一个按weekday将数据轮循备份的脚本:备份的间隔和周期可以根据备份的需求确定
/home/mysql/bin/mysqldump -S/data/app_1/mysql.sock -umysql db_name | gzip -f>/path/to/backup/db_name.`date +%w`.dump.gz
因此写在CRONTAB中一般是:
15 4 * * * /home/mysql/bin/mysqldump -S/data/app_1/mysql.sock -umysql db_name | gzip -f>/path/to/backup/db_name.`date +\%w`.dump.gz
注意:
1 在crontab中'%'需要转义成'\%'
2 根据日志统计,应用负载最低的时候一般是在早上4-6点

先备份在本地然后传到远程的备份服务器上,或者直接建立一个数据库备份帐号,直接在远程的服务器上备份,远程备份只需要将以上脚本中的-S /path/to/msyql.sock改成-h IP.ADDRESS即可。

数据的恢复和系统的升级
======================
日常维护和数据迁移:在数据盘没有被破坏的情况下
硬盘一般是系统中寿命最低的硬件。而系统(包括操作系统和MySQL应用)的升级和硬件升级,都会遇到数据迁移的问题。
只要数据不变,先装好服务器,然后直接将数据盘(硬盘2)安装上,只需要将启动脚本重新加入到rc.local文件中,系统就算是很好的恢复了。

灾难恢复:数据库数据本身被破坏的情况下
确定破坏的时间点,然后从备份数据中恢复。

应用的设计要点
==============
如果MySQL应用占用的CPU超过10%就应该考虑优化了。

  1. 如果这个服务可以被其他非数据库应用代替(比如很多基于数据库的计数器完全可以用WEB日志统计代替)最好将其禁用:
    非用数据库不可吗?虽然数据库的确可以简化很多应用的结构设计,但本身也是一个系统资源消耗比较大的应用。在某些情况下文本,DBM比数据库是更好的选择,比如:很多应用如果没有很高的实时统计需求的话,完全可以先记录到文件日志中,定期的导入到数据库中做后续统计分析。如果还是需要记录简单的2维键-值对应结构的话可以使用类似于DBM的HEAP类型表。因为HEAP表全部在内存中存取,效率非常高,但服务器突然断电时有可能出现数据丢失,所以非常适合存储在线用户信息,日志等临时数据。即使需要使用数据库的,应用如果没有太复杂的数据完整性需求的化,完全可以不使用那些支持外键的商业数据库,比如MySQL。只有非常需要完整的商业逻辑和事务完整性的时候才需要Oracle这样的大型数据库。对于高负载应用来说完全可以把日志文件,DBM,MySQL等轻量级方式做前端数据采集格式,然后用Oracle MSSQL DB2 Sybase等做数据库仓库以完成复杂的数据库挖掘分析工作。
    有朋友和我说用标准的MyISAM表代替了InnoDB表以后,数据库性能提高了20倍。

  2. 数据库服务的主要瓶颈:单个服务的连接数
    对于一个应用来说,如果数据库表结构的设计能够按照数据库原理的范式来设计的话,并且已经使用了最新版本的MySQL,并且按照比较优化的方式运行了,那么最后的主要瓶颈一般在于单个服务的连接数,即使一个数据库可以支持并发500个连接,最好也不要把应用用到这个地步,因为并发连接数过多数据库服务本身用于调度的线程的开销也会非常大了。所以如果应用允许的话:让一台机器多跑几个MySQL服务分担。将服务均衡的规划到多个MySQL服务端口上:比如app_1 ==> 3301 app_2 ==> 3302...app_9 ==> 3309。一个1G内存的机器跑上10个MySQL是很正常的。让10个MySQLD承担1000个并发连接效率要比让2个MySQLD承担1000个效率高的多。当然,这样也会带来一些应用编程上的复杂度;

  3. 使用单独的数据库服务器(不要让数据库和前台WEB服务抢内存),MySQL拥有更多的内存就可能能有效的进行结果集的缓存;在前面的启动脚本中有一个-O key_buffer=32M参数就是用于将缺省的8M索引缓存增加到32M(当然对于)

  4. 应用尽量使用PCONNECT和polling机制,用于节省MySQL服务建立连接的开销,但也会造成MySQL并发链接数过多(每个HTTPD都会对应一个MySQL线程);

  5. 表的横向拆分:让最常被访问的10%的数据放在一个小表里,90%的历史数据放在一个归档表里(所谓:快慢表),数据中间通过定期“搬家”和定期删除无效数据来节省,毕竟大部分应用(比如论坛)访问2个月前数据的几率会非常少,而且价值也不是很高。这样对于应用来说总是在一个比较小的结果级中进行数据选择,比较有利于数据的缓存,不要指望MySQL中对单表记录条数在10万级以上还有比较高的效率。而且有时候数据没有必要做那么精确,比如一个快表中查到了某个人发表的文章有60条结果,快表和慢表的比例是1:20,那么就可以简单的估计这个人一共发表了1200篇。Google的搜索结果数也是一样:对于很多上十万的结果数,后面很多的数字都是通过一定的算法估计出来的。

  6. 数据库字段设计:表的纵向拆分(过渡范化):将所有的定长字段(char, int等)放在一个表里,所有的变长字段(varchar,text,blob等)放在另外一个表里,2个表之间通过主键关联,这样,定长字段表可以得到很大的优化(这样可以使用HEAP表类型,数据完全在内存中存取),这里也说明另外一个原则,对于我们来说,尽量使用定长字段可以通过空间的损失换取访问效率的提高。在MySQL4中也出现了支持外键和事务的InnoDB类型表,标准的MyISAM格式表和基于HASH结构的HEAP内存表,MySQL之所以支持多种表类型,实际上是针对不同应用提供了不同的优化方式;

  7. 仔细的检查应用的索引设计:可以在服务启动参数中加入 --log-slow-queries[=file]用于跟踪分析应用瓶颈,对于跟踪服务瓶颈最简单的方法就是用MySQL的status查看MySQL服务的运行统计和show processlist来查看当前服务中正在运行的SQL,如果某个SQL经常出现在PROCESS LIST中,一。有可能被查询的此时非常多,二,里面有影响查询的字段没有索引,三,返回的结果数过多数据库正在排序(SORTING);所以做一个脚本:比如每2秒运行以下show processlist;把结果输出到文件中,看到底是什么查询在吃CPU。

  8. 全文检索:如果相应字段没有做全文索引的话,全文检索将是一个非常消耗CPU的功能,因为全文检索是用不上一般数据库的索引的,所以要进行相应字段记录遍历。关于全文索引可以参考一下基于Java的全文索引引擎lucene的介绍

  9. 前台应用的记录缓存:比如一个经常使用数据库认证,如果需要有更新用户最后登陆时间的操作,最好记录更新后就把用户放到一个缓存中(设置2个小时后过期),这样如果用户在2个小时内再次使用到登陆,就直接从缓存里认证,避免了过于频繁的数据库操作。

  10. 查询优先的表应该尽可能为where和order by字句中的字段加上索引,数据库更新插入优先的应用索引越少越好。

总之:对于任何数据库单表记录超过100万条优化都是比较困难的,关键是要把应用能够转化成数据库比较擅长的数据上限内。也就是把复杂需求简化成比较成熟的解决方案内。

一次优化实战
============
以下例子是对一个论坛应用进行的优化:

  1. 用Webalizer代替了原来的通过数据库的统计。
  2. 首先通过TOP命令查看MySQL服务的CPU占用左右80%和内存占用:10M,说明数据库的索引缓存已经用完了,修改启动参数,增加了-O key_buffer=32M,过一段时间等数据库稳定后看的内存占用是否达到上限。最后将缓存一直增加到64M,数据库缓存才基本能充分使用。对于一个数据库应用来说,把内存给数据库比给WEB服务实用的多,因为MySQL查询速度的提高能加快web应用从而节省并发的WEB服务所占用的内存资源。
  3. 用show processlist;统计经常出现的SQL:

    每分钟运行一次show processlist并记录日志:
    * * * * * (/home/mysql/bin/mysql -uuser -ppassword < /home/chedong/show_processlist.sql >>  /home/chedong/mysql_processlist.log)

    show_processlist.sql里就一句:
    show processlist;

    比如可以从日志中将包含where的字句过滤出来:
    grep where mysql_processlist.log
    如果发现有死锁,一定要重新审视一下数据库设计了,对于一般情况:查询速度很慢,就将SQL where字句中没有索引的字段加上索引,如果是排序慢就将order by字句中没有索引的字段加上。对于有%like%的查询,考虑以后禁用和使用全文索引加速。

  4. 还是根据show processlist;看经常有那些数据库被频繁使用,考虑将数据库拆分到其他服务端口上。

MSSQL到MySQL的数据迁移:ACCESS+MySQL ODBC Driver

在以前的几次数据迁移实践过程中,我发现最简便的数据迁移过程并不是通过专业的数据库迁移工具,也不是MSSQL自身的DTS进行数据迁移(迁移过程中间会有很多表出错误警告),但通过将MSSQL数据库通过ACCESS获取外部数据导入到数据库中,然后用ACCESS的表==>右键==>导出,制定ODBC,通过MySQL的DSN将数据导出。这样迁移大部分数据都会非常顺利,如果导出的表有索引问题,还会出添加索引提示(DTS就不行),然后剩余的工作就是在MySQL中设计字段对应的SQL脚本了。

参考文档:

MySQL的参考:
http://dev.mysql.com/doc/

posted @ 2008-01-12 17:45 true 阅读(290) | 评论 (0)编辑 收藏

 
守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。 Linux的大多数服务器就是用守护进程实现的。比如,Internet服务器inetd,Web服务器httpd等。同时,守护进程完成许多系统任务。比如,作业规划进程crond,打印进程lpd等。
守护进程的编程本身并不复杂,复杂的是各种版本的Unix的实现机制不尽相同,造成不同 Unix环境下守护进程的编程规则并不一致。需要注意,照搬某些书上的规则(特别是BSD4.3和低版本的System V)到Linux会出现错误的。下面将给出Linux下守护进程的编程要点和详细实例。
一. 守护进程及其特性
守护进程最重要的特性是后台运行。在这一点上DOS下的常驻内存程序TSR与之相似。其次,守护进程必须与其运行前的环境隔离开来。这些环境包括未关闭的文件描述符,控制终端,会话和进程组,工作目录以及文件创建掩模等。这些环境通常是守护进程从执行它的父进程(特别是shell)中继承下来的。最后,守护进程的启动方式有其特殊之处。它可以在Linux系统启动时从启动脚本/etc/rc.d中启动,可以由作业规划进程crond启动,还可以由用户终端(通常是 shell)执行。
总之,除开这些特殊性以外,守护进程与普通进程基本上没有什么区别。因此,编写守护进程实际上是把一个普通进程按照上述的守护进程的特性改造成为守护进程。如果对进程有比较深入的认识就更容易理解和编程了。
二. 守护进程的编程要点
前面讲过,不同Unix环境下守护进程的编程规则并不一致。所幸的是守护进程的编程原则其实都一样,区别在于具体的实现细节不同。这个原则就是要满足守护进程的特性。同时,Linux是基于Syetem V的SVR4并遵循Posix标准,实现起来与BSD4相比更方便。编程要点如下;
1. 在后台运行。
为避免挂起控制终端将Daemon放入后台执行。方法是在进程中调用fork使父进程终止,让Daemon在子进程中后台执行。
if(pid=fork())
exit(0);//是父进程,结束父进程,子进程继续
2. 脱离控制终端,登录会话和进程组
有必要先介绍一下Linux中的进程与控制终端,登录会话和进程组之间的关系:进程属于一个进程组,进程组号(GID)就是进程组长的进程号(PID)。登录会话可以包含多个进程组。这些进程组共享一个控制终端。这个控制终端通常是创建进程的登录终端。
控制终端,登录会话和进程组通常是从父进程继承下来的。我们的目的就是要摆脱它们,使之不受它们的影响。方法是在第1点的基础上,调用setsid()使进程成为会话组长:
setsid();
说明:当进程是会话组长时setsid()调用失败。但第一点已经保证进程不是会话组长。setsid()调用成功后,进程成为新的会话组长和新的进程组长,并与原来的登录会话和进程组脱离。由于会话过程对控制终端的独占性,进程同时与控制终端脱离。
3. 禁止进程重新打开控制终端
现在,进程已经成为无终端的会话组长。但它可以重新申请打开一个控制终端。可以通过使进程不再成为会话组长来禁止进程重新打开控制终端:

if(pid=fork())
exit(0);//结束第一子进程,第二子进程继续(第二子进程不再是会话组长)
4. 关闭打开的文件描述符
进程从创建它的父进程那里继承了打开的文件描述符。如不关闭,将会浪费系统资源,造成进程所在的文件系统无法卸下以及引起无法预料的错误。按如下方法关闭它们:
for(i=0;i 关闭打开的文件描述符close(i);>
5. 改变当前工作目录
进程活动时,其工作目录所在的文件系统不能卸下。一般需要将工作目录改变到根目录。对于需要转储核心,写运行日志的进程将工作目录改变到特定目录如/tmpchdir("/")
6. 重设文件创建掩模
进程从创建它的父进程那里继承了文件创建掩模。它可能修改守护进程所创建的文件的存取位。为防止这一点,将文件创建掩模清除:umask(0);
7. 处理SIGCHLD信号
处理SIGCHLD信号并不是必须的。但对于某些进程,特别是服务器进程往往在请求到来时生成子进程处理请求。如果父进程不等待子进程结束,子进程将成为僵尸进程(zombie)从而占用系统资源。如果父进程等待子进程结束,将增加父进程的负担,影响服务器进程的并发性能。在Linux下可以简单地将 SIGCHLD信号的操作设为SIG_IGN。
signal(SIGCHLD,SIG_IGN);
这样,内核在子进程结束时不会产生僵尸进程。这一点与BSD4不同,BSD4下必须显式等待子进程结束才能释放僵尸进程。
三. 守护进程实例
守护进程实例包括两部分:主程序test.c和初始化程序init.c。主程序每隔一分钟向/tmp目录中的日志test.log报告运行状态。初始化程序中的init_daemon函数负责生成守护进程。读者可以利用init_daemon函数生成自己的守护进程。
1. init.c清单

#include < unistd.h >
#include < signal.h >
#include < sys/param.h >
#include < sys/types.h >
#include < sys/stat.h >
void init_daemon(void)
{
int pid;
int i;
if(pid=fork())
exit(0);//是父进程,结束父进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第一子进程,后台继续执行
setsid();//第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if(pid=fork())
exit(0);//是第一子进程,结束第一子进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长

for(i=0;i< NOFILE;++i)//关闭打开的文件描述符
close(i);
chdir("/tmp");//改变工作目录到/tmp
umask(0);//重设文件创建掩模
return;
}
2. test.c清单
#include < stdio.h >
#include < time.h >

void init_daemon(void);//守护进程初始化函数

main()
{
FILE *fp;
time_t t;
init_daemon();//初始化为Daemon

while(1)//每隔一分钟向test.log报告运行状态
{
sleep(60);//睡眠一分钟
if((fp=fopen("test.log","a")) >=0)
{
t=time(0);
fprintf(fp,"Im here at %sn",asctime(localtime(&t)) );
fclose(fp);
}
}
}
以上程序在RedHat Linux6.0下编译通过。步骤如下:
编译:gcc -g -o test init.c test.c
执行:./test
查看进程:ps -ef
从输出可以发现test守护进程的各种特性满足上面的要求。
posted @ 2007-11-26 10:22 true 阅读(493) | 评论 (1)编辑 收藏

 

一 C++ 中 string与wstring互转

方法一:

string WideToMutilByte(const wstring& _src)
{
int nBufSize = WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, NULL, 0, 0, FALSE);

char *szBuf = new char[nBufSize];

WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, szBuf, nBufSize, 0, FALSE);

string strRet(szBuf);

delete []szBuf;
szBuf = NULL;

return strRet;
}

wstring MutilByteToWide(const string& _src)
{
//计算字符串 string 转成 wchar_t 之后占用的内存字节数
int nBufSize = MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,NULL,0);

//为 wsbuf 分配内存 BufSize 个字节
wchar_t *wsBuf = new wchar_t[nBufSize];

//转化为 unicode 的 WideString
MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,wsBuf,nBufSize);

wstring wstrRet(wsBuf);

delete []wsBuf;
wsBuf = NULL;

return wstrRet;
}

 


转载:csdn

这篇文章里,我将给出几种C++ std::string和std::wstring相互转换的转换方法。
 
第一种方法:调用WideCharToMultiByte()和MultiByteToWideChar(),代码如下(关于详细的解释,可以参考《windows核心编程》):
 

#include <string>
#include <windows.h>
using namespace std;
//Converting a WChar string to a Ansi string
std::string WChar2Ansi(LPCWSTR pwszSrc)
{
         int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
 
         if (nLen<= 0) return std::string("");
 
         char* pszDst = new char[nLen];
         if (NULL == pszDst) return std::string("");
 
         WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
         pszDst[nLen -1] = 0;
 
         std::string strTemp(pszDst);
         delete [] pszDst;
 
         return strTemp;
}

 
string ws2s(wstring& inputws)
{
        return WChar2Ansi(inputws.c_str());
}

 

 
//Converting a Ansi string to WChar string


std::wstring Ansi2WChar(LPCSTR pszSrc, int nLen)
 
{
    int nSize = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pszSrc, nLen, 0, 0);
    if(nSize <= 0) return NULL;
 
         WCHAR *pwszDst = new WCHAR[nSize+1];
    if( NULL == pwszDst) return NULL;
 
    MultiByteToWideChar(CP_ACP, 0,(LPCSTR)pszSrc, nLen, pwszDst, nSize);
    pwszDst[nSize] = 0;
 
    if( pwszDst[0] == 0xFEFF)                    // skip Oxfeff
        for(int i = 0; i < nSize; i ++)
                            pwszDst[i] = pwszDst[i+1];
 
    wstring wcharString(pwszDst);
         delete pwszDst;
 
    return wcharString;
}

 
std::wstring s2ws(const string& s)
{
     return Ansi2WChar(s.c_str(),s.size());
}


 
 
第二种方法:采用ATL封装_bstr_t的过渡:(注,_bstr_是Microsoft Specific的,所以下面代码可以在VS2005通过,无移植性);


#include <string>
#include <comutil.h>
using namespace std;
#pragma comment(lib, "comsuppw.lib")
 
string ws2s(const wstring& ws);
wstring s2ws(const string& s);
 
string ws2s(const wstring& ws)
{
         _bstr_t t = ws.c_str();
         char* pchar = (char*)t;
         string result = pchar;
         return result;
}

 
wstring s2ws(const string& s)
{
         _bstr_t t = s.c_str();
         wchar_t* pwchar = (wchar_t*)t;
         wstring result = pwchar;
         return result;
}


 
第三种方法:使用CRT库的mbstowcs()函数和wcstombs()函数,平台无关,需设定locale。


#include <string>
#include <locale.h>
using namespace std;
string ws2s(const wstring& ws)
{
         string curLocale = setlocale(LC_ALL, NULL);        // curLocale = "C";
 
         setlocale(LC_ALL, "chs");
 
         const wchar_t* _Source = ws.c_str();
         size_t _Dsize = 2 * ws.size() + 1;
         char *_Dest = new char[_Dsize];
         memset(_Dest,0,_Dsize);
         wcstombs(_Dest,_Source,_Dsize);
         string result = _Dest;
         delete []_Dest;
 
         setlocale(LC_ALL, curLocale.c_str());
 
         return result;
}

 
wstring s2ws(const string& s)
{
         setlocale(LC_ALL, "chs");
 
         const char* _Source = s.c_str();
         size_t _Dsize = s.size() + 1;
         wchar_t *_Dest = new wchar_t[_Dsize];
         wmemset(_Dest, 0, _Dsize);
         mbstowcs(_Dest,_Source,_Dsize);
         wstring result = _Dest;
         delete []_Dest;
 
         setlocale(LC_ALL, "C");
 
         return result;
}


二 utf8.utf16.utf32的相互转化

可以参考Unicode.org 上有ConvertUTF.c和ConvertUTF.h (下载地址:http://www.unicode.org/Public/PROGRAMS/CVTUTF/

实现文件ConvertUTF.c:(.h省)
/**//*
 * Copyright 2001-2004 Unicode, Inc.
 *
 * Disclaimer
 *
 * This source code is provided as is by Unicode, Inc. No claims are
 * made as to fitness for any particular purpose. No warranties of any
 * kind are expressed or implied. The recipient agrees to determine
 * applicability of information provided. If this file has been
 * purchased on magnetic or optical media from Unicode, Inc., the
 * sole remedy for any claim will be exchange of defective media
 * within 90 days of receipt.
 *
 * Limitations on Rights to Redistribute This Code
 *
 * Unicode, Inc. hereby grants the right to freely use the information
 * supplied in this file in the creation of products supporting the
 * Unicode Standard, and to make copies of this file in any form
 * for internal or external distribution as long as this notice
 * remains attached.
 */

/**//* ---------------------------------------------------------------------

    Conversions between UTF32, UTF-16, and UTF-8. Source code file.
    Author: Mark E. Davis, 1994.
    Rev History: Rick McGowan, fixes & updates May 2001.
    Sept 2001: fixed const & error conditions per
    mods suggested by S. Parent & A. Lillich.
    June 2002: Tim Dodd added detection and handling of incomplete
    source sequences, enhanced error detection, added casts
    to eliminate compiler warnings.
    July 2003: slight mods to back out aggressive FFFE detection.
    Jan 2004: updated switches in from-UTF8 conversions.
    Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions.

    See the header file "ConvertUTF.h" for complete documentation.

------------------------------------------------------------------------ */


#include "ConvertUTF.h"
#ifdef CVTUTF_DEBUG
#include <stdio.h>
#endif

static const int halfShift  = 10; /**//* used for shifting by 10 bits */

static const UTF32 halfBase = 0x0010000UL;
static const UTF32 halfMask = 0x3FFUL;

#define UNI_SUR_HIGH_START  (UTF32)0xD800
#define UNI_SUR_HIGH_END    (UTF32)0xDBFF
#define UNI_SUR_LOW_START   (UTF32)0xDC00
#define UNI_SUR_LOW_END     (UTF32)0xDFFF
#define false       0
#define true        1

/**//* --------------------------------------------------------------------- */

ConversionResult ConvertUTF32toUTF16 (
    const UTF32** sourceStart, const UTF32* sourceEnd,
    UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF32* source = *sourceStart;
    UTF16* target = *targetStart;
    while (source < sourceEnd) {
    UTF32 ch;
    if (target >= targetEnd) {
        result = targetExhausted; break;
    }
    ch = *source++;
    if (ch <= UNI_MAX_BMP) { /**//* Target is a character <= 0xFFFF */
        /**//* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */
        if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
        if (flags == strictConversion) {
            --source; /**//* return to the illegal value itself */
            result = sourceIllegal;
            break;
        } else {
            *target++ = UNI_REPLACEMENT_CHAR;
        }
        } else {
        *target++ = (UTF16)ch; /**//* normal case */
        }
    } else if (ch > UNI_MAX_LEGAL_UTF32) {
        if (flags == strictConversion) {
        result = sourceIllegal;
        } else {
        *target++ = UNI_REPLACEMENT_CHAR;
        }
    } else {
        /**//* target is a character in range 0xFFFF - 0x10FFFF. */
        if (target + 1 >= targetEnd) {
        --source; /**//* Back up source pointer! */
        result = targetExhausted; break;
        }
        ch -= halfBase;
        *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
        *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
    }
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/**//* --------------------------------------------------------------------- */

ConversionResult ConvertUTF16toUTF32 (
    const UTF16** sourceStart, const UTF16* sourceEnd,
    UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF16* source = *sourceStart;
    UTF32* target = *targetStart;
    UTF32 ch, ch2;
    while (source < sourceEnd) {
    const UTF16* oldSource = source; /**//*  In case we have to back up because of target overflow. */
    ch = *source++;
    /**//* If we have a surrogate pair, convert to UTF32 first. */
    if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
        /**//* If the 16 bits following the high surrogate are in the source buffer */
        if (source < sourceEnd) {
        ch2 = *source;
        /**//* If it's a low surrogate, convert to UTF32. */
        if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
            ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
            + (ch2 - UNI_SUR_LOW_START) + halfBase;
            ++source;
        } else if (flags == strictConversion) { /**//* it's an unpaired high surrogate */
            --source; /**//* return to the illegal value itself */
            result = sourceIllegal;
            break;
        }
        } else { /**//* We don't have the 16 bits following the high surrogate. */
        --source; /**//* return to the high surrogate */
        result = sourceExhausted;
        break;
        }
    } else if (flags == strictConversion) {
        /**//* UTF-16 surrogate values are illegal in UTF-32 */
        if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
        --source; /**//* return to the illegal value itself */
        result = sourceIllegal;
        break;
        }
    }
    if (target >= targetEnd) {
        source = oldSource; /**//* Back up source pointer! */
        result = targetExhausted; break;
    }
    *target++ = ch;
    }
    *sourceStart = source;
    *targetStart = target;
#ifdef CVTUTF_DEBUG
if (result == sourceIllegal) {
    fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2);
    fflush(stderr);
}
#endif
    return result;
}

/**//* --------------------------------------------------------------------- */

/**//*
 * Index into the table below with the first byte of a UTF-8 sequence to
 * get the number of trailing bytes that are supposed to follow it.
 * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
 * left as-is for anyone who may want to do such conversion, which was
 * allowed in earlier algorithms.
 */
static const char trailingBytesForUTF8[256] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

/**//*
 * Magic values subtracted from a buffer value during UTF8 conversion.
 * This table contains as many values as there might be trailing bytes
 * in a UTF-8 sequence.
 */
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
             0x03C82080UL, 0xFA082080UL, 0x82082080UL };

/**//*
 * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
 * into the first byte, depending on how many bytes follow.  There are
 * as many entries in this table as there are UTF-8 sequence types.
 * (I.e., one byte sequence, two byte etc.). Remember that sequencs
 * for *legal* UTF-8 will be 4 or fewer bytes total.
 */
static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };

/**//* --------------------------------------------------------------------- */

/**//* The interface converts a whole buffer to avoid function-call overhead.
 * Constants have been gathered. Loops & conditionals have been removed as
 * much as possible for efficiency, in favor of drop-through switches.
 * (See "Note A" at the bottom of the file for equivalent code.)
 * If your compiler supports it, the "isLegalUTF8" call can be turned
 * into an inline function.
 */

/**//* --------------------------------------------------------------------- */

ConversionResult ConvertUTF16toUTF8 (
    const UTF16** sourceStart, const UTF16* sourceEnd,
    UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF16* source = *sourceStart;
    UTF8* target = *targetStart;
    while (source < sourceEnd) {
    UTF32 ch;
    unsigned short bytesToWrite = 0;
    const UTF32 byteMask = 0xBF;
    const UTF32 byteMark = 0x80;
    const UTF16* oldSource = source; /**//* In case we have to back up because of target overflow. */
    ch = *source++;
    /**//* If we have a surrogate pair, convert to UTF32 first. */
    if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
        /**//* If the 16 bits following the high surrogate are in the source buffer */
        if (source < sourceEnd) {
        UTF32 ch2 = *source;
        /**//* If it's a low surrogate, convert to UTF32. */
        if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
            ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
            + (ch2 - UNI_SUR_LOW_START) + halfBase;
            ++source;
        } else if (flags == strictConversion) { /**//* it's an unpaired high surrogate */
            --source; /**//* return to the illegal value itself */
            result = sourceIllegal;
            break;
        }
        } else { /**//* We don't have the 16 bits following the high surrogate. */
        --source; /**//* return to the high surrogate */
        result = sourceExhausted;
        break;
        }
    } else if (flags == strictConversion) {
        /**//* UTF-16 surrogate values are illegal in UTF-32 */
        if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
        --source; /**//* return to the illegal value itself */
        result = sourceIllegal;
        break;
        }
    }
    /**//* Figure out how many bytes the result will require */
    if (ch < (UTF32)0x80) {         bytesToWrite = 1;
    } else if (ch < (UTF32)0x800) {     bytesToWrite = 2;
    } else if (ch < (UTF32)0x10000) {   bytesToWrite = 3;
    } else if (ch < (UTF32)0x110000) {  bytesToWrite = 4;
    } else {                bytesToWrite = 3;
                        ch = UNI_REPLACEMENT_CHAR;
    }

    target += bytesToWrite;
    if (target > targetEnd) {
        source = oldSource; /**//* Back up source pointer! */
        target -= bytesToWrite; result = targetExhausted; break;
    }
    switch (bytesToWrite) { /**//* note: everything falls through. */
        case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
        case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
        case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
        case 1: *--target =  (UTF8)(ch | firstByteMark[bytesToWrite]);
    }
    target += bytesToWrite;
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/**//* --------------------------------------------------------------------- */

/**//*
 * Utility routine to tell whether a sequence of bytes is legal UTF-8.
 * This must be called with the length pre-determined by the first byte.
 * If not calling this from ConvertUTF8to*, then the length can be set by:
 *  length = trailingBytesForUTF8[*source]+1;
 * and the sequence is illegal right away if there aren't that many bytes
 * available.
 * If presented with a length > 4, this returns false.  The Unicode
 * definition of UTF-8 goes up to 4-byte sequences.
 */

static Boolean isLegalUTF8(const UTF8 *source, int length) {
    UTF8 a;
    const UTF8 *srcptr = source+length;
    switch (length) {
    default: return false;
    /**//* Everything else falls through when "true" */
    case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 2: if ((a = (*--srcptr)) > 0xBF) return false;

    switch (*source) {
        /**//* no fall-through in this inner switch */
        case 0xE0: if (a < 0xA0) return false; break;
        case 0xED: if (a > 0x9F) return false; break;
        case 0xF0: if (a < 0x90) return false; break;
        case 0xF4: if (a > 0x8F) return false; break;
        default:   if (a < 0x80) return false;
    }

    case 1: if (*source >= 0x80 && *source < 0xC2) return false;
    }
    if (*source > 0xF4) return false;
    return true;
}

/**//* --------------------------------------------------------------------- */

/**//*
 * Exported function to return whether a UTF-8 sequence is legal or not.
 * This is not used here; it's just exported.
 */
Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
    int length = trailingBytesForUTF8[*source]+1;
    if (source+length > sourceEnd) {
    return false;
    }
    return isLegalUTF8(source, length);
}

/**//* --------------------------------------------------------------------- */

ConversionResult ConvertUTF8toUTF16 (
    const UTF8** sourceStart, const UTF8* sourceEnd,
    UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF8* source = *sourceStart;
    UTF16* target = *targetStart;
    while (source < sourceEnd) {
    UTF32 ch = 0;
    unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
    if (source + extraBytesToRead >= sourceEnd) {
        result = sourceExhausted; break;
    }
    /**//* Do this check whether lenient or strict */
    if (! isLegalUTF8(source, extraBytesToRead+1)) {
        result = sourceIllegal;
        break;
    }
    /**//*
     * The cases all fall through. See "Note A" below.
     */
    switch (extraBytesToRead) {
        case 5: ch += *source++; ch <<= 6; /**//* remember, illegal UTF-8 */
        case 4: ch += *source++; ch <<= 6; /**//* remember, illegal UTF-8 */
        case 3: ch += *source++; ch <<= 6;
        case 2: ch += *source++; ch <<= 6;
        case 1: ch += *source++; ch <<= 6;
        case 0: ch += *source++;
    }
    ch -= offsetsFromUTF8[extraBytesToRead];

    if (target >= targetEnd) {
        source -= (extraBytesToRead+1); /**//* Back up source pointer! */
        result = targetExhausted; break;
    }
    if (ch <= UNI_MAX_BMP) { /**//* Target is a character <= 0xFFFF */
        /**//* UTF-16 surrogate values are illegal in UTF-32 */
        if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
        if (flags == strictConversion) {
            source -= (extraBytesToRead+1); /**//* return to the illegal value itself */
            result = sourceIllegal;
            break;
        } else {
            *target++ = UNI_REPLACEMENT_CHAR;
        }
        } else {
        *target++ = (UTF16)ch; /**//* normal case */
        }
    } else if (ch > UNI_MAX_UTF16) {
        if (flags == strictConversion) {
        result = sourceIllegal;
        source -= (extraBytesToRead+1); /**//* return to the start */
        break; /**//* Bail out; shouldn't continue */
        } else {
        *target++ = UNI_REPLACEMENT_CHAR;
        }
    } else {
        /**//* target is a character in range 0xFFFF - 0x10FFFF. */
        if (target + 1 >= targetEnd) {
        source -= (extraBytesToRead+1); /**//* Back up source pointer! */
        result = targetExhausted; break;
        }
        ch -= halfBase;
        *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
        *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
    }
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/**//* --------------------------------------------------------------------- */

ConversionResult ConvertUTF32toUTF8 (
    const UTF32** sourceStart, const UTF32* sourceEnd,
    UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF32* source = *sourceStart;
    UTF8* target = *targetStart;
    while (source < sourceEnd) {
    UTF32 ch;
    unsigned short bytesToWrite = 0;
    const UTF32 byteMask = 0xBF;
    const UTF32 byteMark = 0x80;
    ch = *source++;
    if (flags == strictConversion ) {
        /**//* UTF-16 surrogate values are illegal in UTF-32 */
        if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
        --source; /**//* return to the illegal value itself */
        result = sourceIllegal;
        break;
        }
    }
    /**//*
     * Figure out how many bytes the result will require. Turn any
     * illegally large UTF32 things (> Plane 17) into replacement chars.
     */
    if (ch < (UTF32)0x80) {         bytesToWrite = 1;
    } else if (ch < (UTF32)0x800) {     bytesToWrite = 2;
    } else if (ch < (UTF32)0x10000) {   bytesToWrite = 3;
    } else if (ch <= UNI_MAX_LEGAL_UTF32) {  bytesToWrite = 4;
    } else {                bytesToWrite = 3;
                        ch = UNI_REPLACEMENT_CHAR;
                        result = sourceIllegal;
    }
   
    target += bytesToWrite;
    if (target > targetEnd) {
        --source; /**//* Back up source pointer! */
        target -= bytesToWrite; result = targetExhausted; break;
    }
    switch (bytesToWrite) { /**//* note: everything falls through. */
        case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
        case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
        case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
        case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
    }
    target += bytesToWrite;
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/**//* --------------------------------------------------------------------- */

ConversionResult ConvertUTF8toUTF32 (
    const UTF8** sourceStart, const UTF8* sourceEnd,
    UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF8* source = *sourceStart;
    UTF32* target = *targetStart;
    while (source < sourceEnd) {
    UTF32 ch = 0;
    unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
    if (source + extraBytesToRead >= sourceEnd) {
        result = sourceExhausted; break;
    }
    /**//* Do this check whether lenient or strict */
    if (! isLegalUTF8(source, extraBytesToRead+1)) {
        result = sourceIllegal;
        break;
    }
    /**//*
     * The cases all fall through. See "Note A" below.
     */
    switch (extraBytesToRead) {
        case 5: ch += *source++; ch <<= 6;
        case 4: ch += *source++; ch <<= 6;
        case 3: ch += *source++; ch <<= 6;
        case 2: ch += *source++; ch <<= 6;
        case 1: ch += *source++; ch <<= 6;
        case 0: ch += *source++;
    }
    ch -= offsetsFromUTF8[extraBytesToRead];

    if (target >= targetEnd) {
        source -= (extraBytesToRead+1); /**//* Back up the source pointer! */
        result = targetExhausted; break;
    }
    if (ch <= UNI_MAX_LEGAL_UTF32) {
        /**//*
         * UTF-16 surrogate values are illegal in UTF-32, and anything
         * over Plane 17 (> 0x10FFFF) is illegal.
         */
        if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
        if (flags == strictConversion) {
            source -= (extraBytesToRead+1); /**//* return to the illegal value itself */
            result = sourceIllegal;
            break;
        } else {
            *target++ = UNI_REPLACEMENT_CHAR;
        }
        } else {
        *target++ = ch;
        }
    } else { /**//* i.e., ch > UNI_MAX_LEGAL_UTF32 */
        result = sourceIllegal;
        *target++ = UNI_REPLACEMENT_CHAR;
    }
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/**//* ---------------------------------------------------------------------

    Note A.
    The fall-through switches in UTF-8 reading code save a
    temp variable, some decrements & conditionals.  The switches
    are equivalent to the following loop:
    {
        int tmpBytesToRead = extraBytesToRead+1;
        do {
        ch += *source++;
        --tmpBytesToRead;
        if (tmpBytesToRead) ch <<= 6;
        } while (tmpBytesToRead > 0);
    }
    In UTF-8 writing code, the switches on "bytesToWrite" are
    similarly unrolled loops.

   --------------------------------------------------------------------- */

 

三 C++ 的字符串与C#的转化

1)将system::String 转化为C++的string:
// convert_system_string.cpp
// compile with: /clr
#include <string>
#include <iostream>
using namespace std;
using namespace System;

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars =
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

void MarshalString ( String ^ s, wstring& os ) {
   using namespace Runtime::InteropServices;
   const wchar_t* chars =
      (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

int main() {
   string a = "test";
   wstring b = L"test2";
   String ^ c = gcnew String("abcd");

   cout << a << endl;
   MarshalString(c, a);
   c = "efgh";
   MarshalString(c, b);
   cout << a << endl;
   wcout << b << endl;
}


2)将System::String转化为char*或w_char*
// convert_string_to_wchar.cpp
// compile with: /clr
#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >

using namespace System;

int main() {
   String ^str = "Hello";

   // Pin memory so GC can't move it while native function is called
   pin_ptr<const wchar_t> wch = PtrToStringChars(str);
   printf_s("%S\n", wch);

   // Conversion to char* :
   // Can just convert wchar_t* to char* using one of the
   // conversion functions such as:
   // WideCharToMultiByte()
   // wcstombs_s()
   //  etc
   size_t convertedChars = 0;
   size_t  sizeInBytes = ((str->Length + 1) * 2);
   errno_t err = 0;
   char    *ch = (char *)malloc(sizeInBytes);

   err = wcstombs_s(&convertedChars,
                    ch, sizeInBytes,
                    wch, sizeInBytes);
   if (err != 0)
      printf_s("wcstombs_s  failed!\n");

    printf_s("%s\n", ch);
}

posted @ 2007-11-18 19:48 true 阅读(514) | 评论 (0)编辑 收藏

问题描述:大部分的vs.net 2005的用户在新建“win32项目-windows应用程序”的时候,新建的工程都通不过去,出现如下提示:
Solution to “MSVCR80D.dll not found” by hua.
“没有找到MSVCR80D.dll,因此这个应用程序未能启动。重新安装应用程序可能会修复此问题。”的完美解决方案^_^感觉偶做的还不错

问题所在:由于vs.net 2005 采用了一种新的DLL方案,搞成一个exe还要配有一个manifest文件(一般在嵌入文件里了,所以看不到,不过也可以不嵌入,这样会生产一个<程序名>.exe.manifest的文件,没它exe自己就转不了了:)这是个新功能,微软弄了个新工具(mt.exe),结果不好用,好像是fat32下时间戳有问题(在ntfs下这个问题就没有了),搞得manifest有时嵌入不到exe中(默认配置是嵌入的,所以就报错找不到dll了。

解决方案(3个都可以,由以第3个最帅,我做的:):
1.    微软对于这个问题应该也有处理,不过感觉不是很人性化。在“属性->配置属性->清单工具->常规“下有一个”使用FAT32解决办法,把它选成是,就可以了。(注意:一定要先配置这个选项,然后再编译工程,要不然还是不好用:)
2.    找到你的工程的文件夹,如(myproject),找到其下的myproject\myproject\Debug\ myproject.rec,把它删掉(删掉整个Debug目录也可以),重新编译,搞定!
3.    本解决方案是俺独创的,感觉爽多了,可以直接再应用向导中配置,严重符合高级人机界面要求:)好,
1)    首先找到你的vs.net安装目录(如我的是E:\Program Files\Microsoft Visual Studio 8),定位到Microsoft Visual Studio 8\VC\VCWizards\AppWiz\Generic\Application文件夹,备份这个Application文件夹,不然一会你自己改咂了我可不管啊:)。
2)    打开html\2052,看到两个文件了吧,就那个AppSettings.htm了,这个管着你的那个配置向导的界面,用UE(不要告诉我你不知道ue啥东西,baidu it)打开,在266行“                </SPAN>”后回车,然后插入一下内容:
<!-- this (hua)section is added by HUA. -->
                    <br><br><br><br><br>
                    
                <span class="itemTextTop" id="FILE_SYSTEM_SPAN" title="">选择你所使用的文件系统:
                    
                       <P CLASS="Spacer"> </P>
                    
                        <INPUT TYPE="radio" CLASS="Radio" checked onPropertyChange="" NAME="filesystem" ID="FAT32" ACCESSKEY="F" TITLE="FAT32">
                        <DIV CLASS="itemTextRadioB" ID="FAT32_DIV" TITLE="FAT32">
                        <LABEL FOR="FAT32" ID="FAT32_LABEL">FAT32(<U>F</U>)</LABEL>
                        </DIV>

                      <BR>

                        <INPUT TYPE="radio" CLASS="Radio" onPropertyChange="" NAME="filesystem" ID="NTFS" ACCESSKEY="N" TITLE="NTFS">
                        <DIV CLASS="itemTextRadioB" ID="NTFS_DIV" TITLE="NTFS">
                        <LABEL FOR="NTFS" ID="NTFS_LABEL">NTFS(<U>N</U>)</LABEL>
                        </DIV>
                </span>
<!-- end of (hua)section -->
好,保存关闭,这个改完了,准备下一个。

3)    打开scripts\2052,这里就一个文件,ue打开它,找到138行“        var bATL = wizard.FindSymbol("SUPPORT_ATL");”其后回车,插入如下内容:
// this (hua)section is added by HUA.
        var MFTool = config.Tools("VCManifestTool");
        MFTool.UseFAT32Workaround = true;
// end of (hua)section    
        好,继续找到210行(源文件的210,你加了上边的语句就不是210了:)“        config = proj.Object.Configurations.Item("Release");”注意这次要在这行“前边”加如下内容:
// this (hua)section is added by HUA.
        if(bFAT32)
        {
            var MFTool = config.Tools("VCManifestTool");
            MFTool.UseFAT32Workaround = true;
        }
// end of (hua)section    
好了,终于都改完了,打开你的vs.net 2005新建一个win32应用程序看看吧,效果还不错吧:)为了这个问题,耽误了我一天的考研复习时间,希望大家能用的上。
另外附个国外的bbs:http://forums.microsoft.com/MSDN/default.aspx?SiteID=1
Msdn的,肯定不错了,上边有vs.net的开发人员活动,都是很官方的东西,大家可以看看,不过英语要够好哦:)
posted @ 2007-11-17 01:37 true 阅读(578) | 评论 (0)编辑 收藏

(一) 先讲一下XML中的物殊字符,手动填写时注意一下。

字符                  字符实体
&                      &amp;或&
'                      &apos;或'
>                      &gt;或>
<                      &lt;或&<
"                       &quot;或"

(二) CMarkup类的源代码。

这是目前的最新版本;

这是官网示例文件,取出里面的Markup.cpp和Markup.h,导入你的工程里面,CMarkup类就可以用了;

下载地址:http://www.firstobject.com/Markup83.zip

(三) 创建一个XML文档。

CMarkup xml;
xml.AddElem( "ORDER" );
xml.AddChildElem( "ITEM" );
xml.IntoElem();
xml.AddChildElem( "SN", "132487A-J" );
xml.AddChildElem( "NAME", "crank casing" );
xml.AddChildElem( "QTY", "1" );
xml.Save("c:\\UserInfo.xml");

效果如下:

<ORDER>
<ITEM>
<SN>132487A-J</SN>
<NAME>crank casing</NAME>
<QTY>1</QTY>
</ITEM>
</ORDER>
(四) 浏览特定元素
CMarkup xml;
xml.Load("UserInfo.xml");
while ( xml.FindChildElem("ITEM") ) {     xml.IntoElem();     xml.FindChildElem( "SN" );     CString csSN = xml.GetChildData();     xml.FindChildElem( "QTY" );     int nQty = atoi( xml.GetChildData() );     xml.OutOfElem(); }
(五)增加元素和属性
添加在最后面,使用的是AddElem;添加在最前面,使用InsertElem。
CMarkup xml;
xml.Load("c:\\UserInfo.xml");
xml.AddElem( "ORDER" );
xml.IntoElem(); // 进入 ORDER



    xml.AddElem( "ITEM" );     xml.IntoElem(); // 进入 ITEM     xml.AddElem( "SN", "4238764-A" ); //添加元素     xml.AddElem( "NAME", "bearing" );//添加元素     xml.AddElem( "QTY", "15" );//添加元素     xml.OutOfElem(); // 退出 ITEM 
xml.AddElem( "SHIPMENT" );
xml.IntoElem(); // 进入 SHIPMENT
xml.AddElem( "POC" );//添加元素
xml.SetAttrib( "type", "non-emergency");//添加属性
xml.IntoElem(); // 进入 POC
xml.AddElem( "NAME", "John Smith");//添加元素
xml.AddElem( "TEL", "555-1234");//添加元素
xml.Save("c:\\UserInfo.xml");

 

效果如下:

<ORDER>
<ITEM>
<SN>132487A-J</SN>
<NAME>crank casing</NAME>
<QTY>1</QTY>
</ITEM>
<ITEM>
<SN>4238764-A</SN>
<NAME>bearing</NAME>
<QTY>15</QTY>
</ITEM>
<SHIPMENT>
<POC type="non-emergency">
<NAME>John Smith</NAME>
<TEL>555-1234</TEL>
</POC>
</SHIPMENT>
</ORDER>

(六) 修改元素和属性

如将POC中的属性type改成:change;

元素TEL改成:123456789

       CMarkup xml;
 if (xml.Load("UserInfo.xml"))
 {
  CString strUserID = _T("");
  xml.ResetMainPos();
  if (xml.FindChildElem("SHIPMENT"))
  {
   xml.IntoElem();
   if (xml.FindChildElem("POC"))
   {
    xml.IntoElem();
    CString str_type=xml.GetAttrib("type");
    MessageBox(str_type);
    xml.SetAttrib("type","change");
    strUserID = xml.GetData();
    
    if (xml.FindChildElem("TEL"))
    {
     xml.IntoElem();
     xml.SetData("123456789");
     xml.Save("UserInfo.xml");
     return;
    }
   }
  }
 }

(七)删除元素:

删除SN=132487A-J的项目。

CMarkup xml;
 if (xml.Load("UserInfo.xml"))
 {
  CString strUserID = _T("");
  xml.ResetMainPos();
  if (xml.FindChildElem("ITEM"))
  {
   xml.IntoElem();
   CString str_sn;
   xml.FindChildElem("SN");
   str_sn=xml.GetChildData();
   if(str_sn=="132487A-J")
   {
    xml.RemoveElem();
    xml.Save("UserInfo.xml");
   }
  }
 }

posted @ 2007-11-15 22:02 true 阅读(858) | 评论 (0)编辑 收藏

awk 用法小结

awk 用法:awk ' pattern {action} '

变量名 含义
ARGC 命令行变元个数
ARGV 命令行变元数组
FILENAME 当前输入文件名
FNR 当前文件中的记录号
FS 输入域分隔符,默认为一个空格
RS 输入记录分隔符
NF 当前记录里域个数
NR 到目前为止记录数
OFS 输出域分隔符
ORS 输出记录分隔符

1、awk '/101/' file 显示文件file中包含101的匹配行。
awk '/101/,/105/' file
awk '$1 == 5' file
awk '$1 == "CT"' file 注意必须带双引号
awk '$1 * $2 >100 ' file
awk '$2 >5 && $2<=15' file
2、awk '{print NR,NF,$1,$NF,}' file 显示文件file的当前记录号、域数和每一行的第一个和最后一个域。
awk '/101/ {print $1,$2 + 10}' file 显示文件file的匹配行的第一、二个域加10。
awk '/101/ {print $1$2}' file
awk '/101/ {print $1 $2}' file 显示文件file的匹配行的第一、二个域,但显示时域中间没有分隔符。
3、df | awk '$4>1000000 ' 通过管道符获得输入,如:显示第4个域满足条件的行。
4、awk -F "|" '{print $1}' file 按照新的分隔符“|”进行操作。
awk 'BEGIN { FS="[: \t|]" }
{print $1,$2,$3}' file 通过设置输入分隔符(FS="[: \t|]")修改输入分隔符。

Sep="|"
awk -F $Sep '{print $1}' file 按照环境变量Sep的值做为分隔符。
awk -F '[ :\t|]' '{print $1}' file 按照正则表达式的值做为分隔符,这里代表空格、:、TAB、|同时做为分隔符。
awk -F '[][]' '{print $1}' file 按照正则表达式的值做为分隔符,这里代表[、]
5、awk -f awkfile file 通过文件awkfile的内容依次进行控制。
cat awkfile
/101/{print "\047 Hello! \047"} --遇到匹配行以后打印 ' Hello! '.\047代表单引号。
{print $1,$2} --因为没有模式控制,打印每一行的前两个域。
6、awk '$1 ~ /101/ {print $1}' file 显示文件中第一个域匹配101的行(记录)。
7、awk 'BEGIN { OFS="%"}
{print $1,$2}' file 通过设置输出分隔符(OFS="%")修改输出格式。
8、awk 'BEGIN { max=100 ;print "max=" max} BEGIN 表示在处理任意行之前进行的操作。
{max=($1 >max ?$1:max); print $1,"Now max is "max}' file 取得文件第一个域的最大值。
(表达式1?表达式2:表达式3 相当于:
if (表达式1)
表达式2
else
表达式3
awk '{print ($1>4 ? "high "$1: "low "$1)}' file
9、awk '$1 * $2 >100 {print $1}' file 显示文件中第一个域匹配101的行(记录)。
10、awk '{$1 == 'Chi' {$3 = 'China'; print}' file 找到匹配行后先将第3个域替换后再显示该行(记录)。
awk '{$7 %= 3; print $7}' file 将第7域被3除,并将余数赋给第7域再打印。
11、awk '/tom/ {wage=$2+$3; printf wage}' file 找到匹配行后为变量wage赋值并打印该变量。
12、awk '/tom/ {count++;}
END {print "tom was found "count" times"}' file END表示在所有输入行处理完后进行处理。
13、awk 'gsub(/\$/,"");gsub(/,/,""); cost+=$4;
END {print "The total is $" cost>"filename"}' file gsub函数用空串替换$和,再将结果输出到filename中。
1 2 3 $1,200.00
1 2 3 $2,300.00
1 2 3 $4,000.00

awk '{gsub(/\$/,"");gsub(/,/,"");
if ($4>1000&&$4<2000) c1+=$4;
else if ($4>2000&&$4<3000) c2+=$4;
else if ($4>3000&&$4<4000) c3+=$4;
else c4+=$4; }
END {printf "c1=[%d];c2=[%d];c3=[%d];c4=[%d]\n",c1,c2,c3,c4}"' file
通过if和else if完成条件语句

awk '{gsub(/\$/,"");gsub(/,/,"");
if ($4>3000&&$4<4000) exit;
else c4+=$4; }
END {printf "c1=[%d];c2=[%d];c3=[%d];c4=[%d]\n",c1,c2,c3,c4}"' file
通过exit在某条件时退出,但是仍执行END操作。
awk '{gsub(/\$/,"");gsub(/,/,"");
if ($4>3000) next;
else c4+=$4; }
END {printf "c4=[%d]\n",c4}"' file
通过next在某条件时跳过该行,对下一行执行操作。


14、awk '{ print FILENAME,$0 }' file1 file2 file3>fileall 把file1、file2、file3的文件内容全部写到fileall中,格式为
打印文件并前置文件名。
15、awk ' $1!=previous { close(previous); previous=$1 }
{print substr($0,index($0," ") +1)>$1}' fileall 把合并后的文件重新分拆为3个文件。并与原文件一致。
16、awk 'BEGIN {"date"|getline d; print d}' 通过管道把date的执行结果送给getline,并赋给变量d,然后打印。
17、awk 'BEGIN {system("echo \"Input your name:\\c\""); getline d;print "\nYour name is",d,"\b!\n"}'
通过getline命令交互输入name,并显示出来。
awk 'BEGIN {FS=":"; while(getline< "/etc/passwd" >0) { if($1~"050[0-9]_") print $1}}'
打印/etc/passwd文件中用户名包含050x_的用户名。

18、awk '{ i=1;while(i<NF) {print NF,$i;i++}}' file 通过while语句实现循环。
awk '{ for(i=1;i<NF;i++) {print NF,$i}}' file 通过for语句实现循环。
type file|awk -F "/" '
{ for(i=1;i<NF;i++)
{ if(i==NF-1) { printf "%s",$i }
else { printf "%s/",$i } }}' 显示一个文件的全路径。
用for和if显示日期
awk 'BEGIN {
for(j=1;j<=12;j++)
{ flag=0;
printf "\n%d月份\n",j;
for(i=1;i<=31;i++)
{
if (j==2&&i>28) flag=1;
if ((j==4||j==6||j==9||j==11)&&i>30) flag=1;
if (flag==0) {printf "%02d%02d ",j,i}
}
}
}'
19、在awk中调用系统变量必须用单引号,如果是双引号,则表示字符串
Flag=abcd
awk '{print '$Flag'}' 结果为abcd
awk '{print "$Flag"}' 结果为$Flag
posted @ 2007-11-13 12:02 true 阅读(389) | 评论 (0)编辑 收藏

一、 简单查询

  简单的Transact-SQL查询只包括选择列表、FROM子句和WHERE子句。它们分别说明所查询列、查询的表或视图、以及搜索条件等。
  例如,下面的语句查询testtable表中姓名为"张三"的nickname字段和email字段。

   SELECT nickname,email
  FROM testtable
  WHERE name='张三'

  (一) 选择列表

  选择列表(select_list)指出所查询列,它可以是一组列名列表、星号、表达式、变量(包括局部变量和全局变量)等构成。

  1、选择所有列

  例如,下面语句显示testtable表中所有列的数据:

   SELECT *
  FROM testtable

  2、选择部分列并指定它们的显示次序

  查询结果集合中数据的排列顺序与选择列表中所指定的列名排列顺序相同。
  例如:

   SELECT nickname,email
  FROM testtable

  3、更改列标题

  在选择列表中,可重新指定列标题。定义格式为:
  列标题=列名
  列名 列标题
  如果指定的列标题不是标准的标识符格式时,应使用引号定界符,例如,下列语句使用汉字显示列标题:

   SELECT 昵称=nickname,电子邮件=email
  FROM testtable

  4、删除重复行

  SELECT语句中使用ALL或DISTINCT选项来显示表中符合条件的所有行或删除其中重复的数据行,默认为ALL。使用DISTINCT选项时,对于所有重复的数据行在SELECT返回的结果集合中只保留一行。

  5、限制返回的行数

  使用TOP n [PERCENT]选项限制返回的数据行数,TOP n说明返回n行,而TOP n PERCENT时,说明n是表示一百分数,指定返回的行数等于总行数的百分之几。
  例如:

   SELECT TOP 2 *
  FROM testtable
  SELECT TOP 20 PERCENT *
  FROM testtable

  (二)FROM子句

  FROM子句指定SELECT语句查询及与查询相关的表或视图。在FROM子句中最多可指定256个表或视图,它们之间用逗号分隔。
  在FROM子句同时指定多个表或视图时,如果选择列表中存在同名列,这时应使用对象名限定这些列所属的表或视图。例如在usertable和citytable表中同时存在cityid列,在查询两个表中的cityid时应使用下面语句格式加以限定:

    SELECT username,citytable.cityid
  FROM usertable,citytable
  WHERE usertable.cityid=citytable.cityid

  在FROM子句中可用以下两种格式为表或视图指定别名:
  表名 as 别名
  表名 别名

  (二) FROM子句

  FROM子句指定SELECT语句查询及与查询相关的表或视图。在FROM子句中最多可指定256个表或视图,它们之间用逗号分隔。
  在FROM子句同时指定多个表或视图时,如果选择列表中存在同名列,这时应使用对象名限定这些列所属的表或视图。例如在usertable和citytable表中同时存在cityid列,在查询两个表中的cityid时应使用下面语句格式加以限定:

   SELECT username,citytable.cityid
  FROM usertable,citytable
  WHERE usertable.cityid=citytable.cityid

  在FROM子句中可用以下两种格式为表或视图指定别名:
  表名 as 别名
  表名 别名
  例如上面语句可用表的别名格式表示为:

   SELECT username,b.cityid
  FROM usertable a,citytable b
  WHERE a.cityid=b.cityid

  SELECT不仅能从表或视图中检索数据,它还能够从其它查询语句所返回的结果集合中查询数据。

  例如:

    SELECT a.au_fname+a.au_lname
  FROM authors a,titleauthor ta
  (SELECT title_id,title
  FROM titles
  WHERE ytd_sales>10000
  ) AS t
  WHERE a.au_id=ta.au_id
  AND ta.title_id=t.title_id

  此例中,将SELECT返回的结果集合给予一别名t,然后再从中检索数据。

  (三) 使用WHERE子句设置查询条件

  WHERE子句设置查询条件,过滤掉不需要的数据行。例如下面语句查询年龄大于20的数据:

   SELECT *
  FROM usertable
  WHERE age>20

  WHERE子句可包括各种条件运算符:
  比较运算符(大小比较):>、>=、=、<、<=、<>、!>、!<
  范围运算符(表达式值是否在指定的范围):BETWEEN...AND...
  NOT BETWEEN...AND...
  列表运算符(判断表达式是否为列表中的指定项):IN (项1,项2......)
  NOT IN (项1,项2......)
  模式匹配符(判断值是否与指定的字符通配格式相符):LIKE、NOT LIKE
  空值判断符(判断表达式是否为空):IS NULL、NOT IS NULL
  逻辑运算符(用于多条件的逻辑连接):NOT、AND、OR

  1、范围运算符例:age BETWEEN 10 AND 30相当于age>=10 AND age<=30
  2、列表运算符例:country IN ('Germany','China')
  3、模式匹配符例:常用于模糊查找,它判断列值是否与指定的字符串格式相匹配。可用于char、varchar、text、ntext、datetime和smalldatetime等类型查询。
  可使用以下通配字符:
  百分号%:可匹配任意类型和长度的字符,如果是中文,请使用两个百分号即%%。
  下划线_:匹配单个任意字符,它常用来限制表达式的字符长度。
  方括号[]:指定一个字符、字符串或范围,要求所匹配对象为它们中的任一个。[^]:其取值也[] 相同,但它要求所匹配对象为指定字符以外的任一个字符。
  例如:
  限制以Publishing结尾,使用LIKE '%Publishing'
  限制以A开头:LIKE '[A]%'
  限制以A开头外:LIKE '[^A]%'

  4、空值判断符例WHERE age IS NULL

  5、逻辑运算符:优先级为NOT、AND、OR

  (四)查询结果排序

  使用ORDER BY子句对查询返回的结果按一列或多列排序。ORDER BY子句的语法格式为:
  ORDER BY {column_name [ASC|DESC]} [,...n]
  其中ASC表示升序,为默认值,DESC为降序。ORDER BY不能按ntext、text和image数据类型进行排
  序。
  例如:

    SELECT *
  FROM usertable
  ORDER BY age desc,userid ASC

  另外,可以根据表达式进行排序。

  二、 联合查询

  UNION运算符可以将两个或两个以上上SELECT语句的查询结果集合合并成一个结果集合显示,即执行联合查询。UNION的语法格式为:

    select_statement
  UNION [ALL] selectstatement
  [UNION [ALL] selectstatement][...n]

  其中selectstatement为待联合的SELECT查询语句。

  ALL选项表示将所有行合并到结果集合中。不指定该项时,被联合查询结果集合中的重复行将只保留一行。

  联合查询时,查询结果的列标题为第一个查询语句的列标题。因此,要定义列标题必须在第一个查询语句中定义。要对联合查询结果排序时,也必须使用第一查询语句中的列名、列标题或者列序号。

  在使用UNION 运算符时,应保证每个联合查询语句的选择列表中有相同数量的表达式,并且每个查询选择表达式应具有相同的数据类型,或是可以自动将它们转换为相同的数据类型。在自动转换时,对于数值类型,系统将低精度的数据类型转换为高精度的数据类型。

  在包括多个查询的UNION语句中,其执行顺序是自左至右,使用括号可以改变这一执行顺序。例如:

  查询1 UNION (查询2 UNION 查询3)

  三、连接查询

  通过连接运算符可以实现多个表查询。连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志。

  在关系数据库管理系统中,表建立时各数据之间的关系不必确定,常把一个实体的所有信息存放在一个表中。当检索数据时,通过连接操作查询出存放在多个表中的不同实体的信息。连接操作给用户带来很大的灵活性,他们可以在任何时候增加新的数据类型。为不同实体创建新的表,尔后通过连接进行查询。

  连接可以在SELECT 语句的FROM子句或WHERE子句中建立,似是而非在FROM子句中指出连接时有助于将连接操作与WHERE子句中的搜索条件区分开来。所以,在Transact-SQL中推荐使用这种方法。

  SQL-92标准所定义的FROM子句的连接语法格式为:

   FROM join_table join_type join_table
  [ON (join_condition)]

  其中join_table指出参与连接操作的表名,连接可以对同一个表操作,也可以对多表操作,对同一个表操作的连接又称做自连接。

  join_type 指出连接类型,可分为三种:内连接、外连接和交叉连接。内连接(INNER JOIN)使用比较运算符进行表间某(些)列数据的比较操作,并列出这些表中与连接条件相匹配的数据行。根据所使用的比较方式不同,内连接又分为等值连接、自然连接和不等连接三种。外连接分为左外连接(LEFT OUTER JOIN或LEFT JOIN)、右外连接(RIGHT OUTER JOIN或RIGHT JOIN)和全外连接(FULL OUTER JOIN或FULL JOIN)三种。与内连接不同的是,外连接不只列出与连接条件相匹配的行,而是列出左表(左外连接时)、右表(右外连接时)或两个表(全外连接时)中所有符合搜索条件的数据行。

  交叉连接(CROSS JOIN)没有WHERE 子句,它返回连接表中所有数据行的笛卡尔积,其结果集合中的数据行数等于第一个表中符合查询条件的数据行数乘以第二个表中符合查询条件的数据行数。

  连接操作中的ON (join_condition) 子句指出连接条件,它由被连接表中的列和比较运算符、逻辑运算符等构成。

  无论哪种连接都不能对text、ntext和image数据类型列进行直接连接,但可以对这三种列进行间接连接。例如:

   SELECT p1.pub_id,p2.pub_id,p1.pr_info
  FROM pub_info AS p1 INNER JOIN pub_info AS p2
  ON DATALENGTH(p1.pr_info)=DATALENGTH(p2.pr_info)

  (一)内连接
  内连接查询操作列出与连接条件匹配的数据行,它使用比较运算符比较被连接列的列值。内连接分三种:
  1、等值连接:在连接条件中使用等于号(=)运算符比较被连接列的列值,其查询结果中列出被连接表中的所有列,包括其中的重复列。
  2、不等连接: 在连接条件使用除等于运算符以外的其它比较运算符比较被连接的列的列值。这些运算符包括>、>=、<=、<、!>、!<和<>。
  3、自然连接:在连接条件中使用等于(=)运算符比较被连接列的列值,但它使用选择列表指出查询结果集合中所包括的列,并删除连接表中的重复列。
  例,下面使用等值连接列出authors和publishers表中位于同一城市的作者和出版社:

   SELECT *
  FROM authors AS a INNER JOIN publishers AS p
  ON a.city=p.city
  又如使用自然连接,在选择列表中删除authors 和publishers 表中重复列(city和state):
  SELECT a.*,p.pub_id,p.pub_name,p.country
  FROM authors AS a INNER JOIN publishers AS p
  ON a.city=p.city

  (二)外连接
  内连接时,返回查询结果集合中的仅是符合查询条件( WHERE 搜索条件或 HAVING 条件)和连接条件的行。而采用外连接时,它返回到查询结果集合中的不仅包含符合连接条件的行,而且还包括左表(左外连接时)、右表(右外连接时)或两个边接表(全外连接)中的所有数据行。如下面使用左外连接将论坛内容和作者信息连接起来:

   SELECT a.*,b.* FROM luntan LEFT JOIN usertable as b
  ON a.username=b.username

  下面使用全外连接将city表中的所有作者以及user表中的所有作者,以及他们所在的城市:

    SELECT a.*,b.*
  FROM city as a FULL OUTER JOIN user as b
  ON a.username=b.username

  (三)交叉连接
  交叉连接不带WHERE 子句,它返回被连接的两个表所有数据行的笛卡尔积,返回到结果集合中的数据行数等于第一个表中符合查询条件的数据行数乘以第二个表中符合查询条件的数据行数。例,titles表中有6类图书,而publishers表中有8家出版社,则下列交叉连接检索到的记录数将等于6*8=48行。
   SELECT type,pub_name
  FROM titles CROSS JOIN publishers
  ORDER BY type

修改字段属性

alter table tablename modify id int(10) unsigned auto_increment primary key not null

修改默认值

alter table tablename alter id default 0

给字段增加primary key

alter table tablename add primary key(id);

删除primary key

1、alter table tablename drop primary key;

2、drop primary key on tablename;


查看table表结构

show create table tableName;


修改table表数据引擎

alter table tableName ENGINE = MyISAM (InnoDB);

增加字段
ALTER TABLE `table` ADD `field` INT(11) UNSIGNED NOT NULL

删除字段

alert table 'table' drop 'field'

 

posted @ 2007-09-05 14:49 true 阅读(581) | 评论 (0)编辑 收藏

MySQL使用tips

作者:叶金荣 (Email:imysql@gmail.com) 来源:http://imysql.cn (2006-07-12 17:05:03)


1、用mysql内置函数转换ip地址和数字
利用两个内置函数
inet_aton:将ip地址转换成数字型
inet_ntoa:将数字型转换成ip地址

2、充分利用mysql内置的format函数
尤其是在处理字符格式的时候,例如将12345转换成12,345这样的,只要用:format(12345,0)即可,如果用format(12345,2)则显示的是12,345.00了...

3、利用mysql的内置函数处理时间戳问题
eg : select FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x');
结果: 2004 3rd August 03:35:48 2004

4、利用mysql_convert_table_format转换表类型
需要DBI和DBD的mysql相关模块支持才能用,例子:
mysql_convert_table_format --user=root --password='xx' --type=myisam test yejr

5、修改mysql表中的字段名
alter table tb_name change old_col new_col definition...

6、利用临时变量
select @var1:=a1+a2 as a_sum,@var2:=b1+b2 as b_sum,@var1+@var2 as total_sum from test_table xxx;

7、用int类型存储ip地址
原先错误的认为必须用bigint才够,后来发现使用int unsigned类型就足够了。 :)

8、CREATE TABLE IF NOT EXISTS ... select 语法局限
尽管只是对目标表的insert操作,但是‘居然’不允许源表的insert操作,真是莫名其妙

9、利用IF函数快速修改ENUM字段值
一个例子:
update rule set enable = if('0' = enable,'1','0') where xxx;
enable 类型:enum('0','1') not null default '0'

10、事务无法嵌套

11、避免长时间的sleep连接造成的连接数超出问题
设定全局变量 wait_timeout 和 interactive_timeout 为比较小的值,例如 10(s),就能使每个sleep连接在10s之后如果还没有查询的话自动断开。

(http://www.fanqiang.com)
posted @ 2007-08-30 10:20 true 阅读(246) | 评论 (0)编辑 收藏

http://www.codeproject.com/macro/KingsTools.asp

Kings Tools

Kings Tools

Introduction

As good as Visual Studio .NET is, I still miss some features in it. But MS knew that they couldn't fulfill every wish so they provided a way to write addins. That's what I've done. Sure, most of the functions in my Tools could also be done with macros, but I wanted them all packed together with an installer.

Tools

  • Run Doxygen
  • Insert Doxygen comments
  • Build Solution stats
  • Dependency Graph
  • Inheritance Graph
  • Swap .h<->.cpp
  • Colorize
  • } End of
  • #region/#endregion for c++
  • Search the web

Run Doxygen

This command first pops up a dialog box in which you can configure the output Doxygen should produce. For those who don't know Doxygen: it's a free tool to generate source documentations. It can produce documentation in different formats like html and even windows help format! See http://www.doxygen.org/ for details. Since the dialog box doesn't offer all possible settings for doxygen, you can always edit the file Doxyfile.cfg manually which is created the first time you run it. All settings in that file override the settings you enter in the dialog box.

Doxygen configuration dialog

If you set Doxygen to generate html output, the resulting index.html is opened inside the IDE. A winhelp output (index.chm) will be opened outside the IDE.

The command available from the Tools menu builds the documentation for the whole solution. If you don't want that for example if you have several third party projects in your solution then you can build the documentation also for single projects. To do that the KingsTools add a command to the right click menu in the solution explorer.

If you want to update Doxygen to a newer version (as soon as one is released) simply overwrite the doxygen.exe in the installation directory. The same applies to the dot.exe.

TODO: find a way to integrate the generated windows help file into VS help.

Insert Doxygen comments

Doxygen needs comments that follow certain conventions to build documentation from. This part of the tools inserts them for you. Either from the right click menu in the code editor window or from the submenu under Tools->Kings Tools. Just place the caret over a method or class header. The inserted comment for a method or function would look like this:

				/**
*
* \param one
* \param two
* \param three
* \return
*/
BOOL myfunction(int one, int two, int three);

You now have to simply insert a description in the second comment line and descriptions for each parameter of the function/method. And of course a description of the return value.

You can customize the function comments by editing the files "functionheadertop.txt", "functionparams.txt" and "functionheaderbottom.txt". Please read the comments inside those files on how to do that. If you don't want to change the function comments for all your projects then you can place any of those files into your project directory (that way it will be used for your project) or inside the folder of your source files (that way it will be used only for the files inside that specific folder).

The inserted comment for a class looks like this:

				/**
* \ingroup projectname
*
* \par requirements
* win98 or later, win2k or later, win95 with IE4 or later, winNT4 with IE4
* or later
*
* \author user
*
* \par license
* This code is absolutely free to use and modify. The code is provided
* "as is" with no expressed or implied warranty. The author accepts no
* liability if it causes any damage to your computer, causes your pet to
* fall ill, increases baldness or makes your car start emitting strange
* noises when you start it up. This code has no bugs, just undocumented
* features!
*
* \version 1.0
* \date 06-2002
* \todo
* \bug
* \warning
*
*/
class CRegBase

The '\ingroup projectname' means that the class is inside the project 'projectname'. That statement helps Doxygen to group classes together. Insert the description of the class right after that statement. If you want to include pictures to illustrate the class, use '\image html "picture.jpg"'. For more helpful tags you can use please check out the Doxygen website. The '\par requirements' section you have to modify yourself to fit the truth of your class. It's not necessary for Doxygen, but I found it very useful to give that information inside a class documentation. The name after the '\author' tag is the currently logged in user. Maybe you want to change that too to include an email address.

You can customize the class comments by editing the file "classheader.txt" Please read the comments inside that file on how to do that. If you don't want to change the class comments for all your projects then you can place that files into your project directory (that way it will be used for your project) or inside the folder of your source files (that way it will be used only for the files inside that specific folder).

The last few tags should be self-explanatory. Under the line '\version' I usually insert short descriptions of what changed between versions.

Build Solution stats

This is a simple line counter. It counts all the lines of all files in your solution, grouped by projects. The generated html file with the counted lines (code, comments, empty) is then opened in the IDE. Since I haven't found a way to add a file directly to a solution and not to a project the file is just opened for view in the IDE.

Dependency and Inheritance graph

These two commands build graphs of the class relations in your solution. See my previous article about this. The difference to my old tool is that it now generates graphs for all projects in the solution and puts all the graphs in one single html page.

Swap .h<->.cpp

This is something a simple macro could also do: it swaps between header and code files. For better accessibility it also is on the right click menu of the code editor. Really nothing special but it can be useful sometimes.

Colorize

This tool goes through all files of the current solution and looks for class, function and macronames. It then writes them to a usertype.dat file, makes the IDE to read that file and deletes it again. After you run this tool, all class, function and macronames of your solution appear colored in the code editor. Default color is the same color as normal keywords, but you can change that under Tools->Options, in the Options dialog select Environment->Fonts and Colors.

If you don't want the colors anymore, just run the command 'disable coloring' and everything will be in normal colors again. I didn't want to overwrite some possible usertype.dat file already created by some user so the tool simply creates a temporary usertype.dat file instead. If you want to have the colors again the next time the IDE starts, you either have to rerun the command (doesn't take very long to execute) or change the code of the tool yourself.

} End of

Have you ever wrote a bunch of code which looked like this:

Braces without comments

Ok, I admit this isn't a very good style of programming, but sometimes it can't be avoided. And in those cases the code is horrible to read because you don't know which closing brace belongs to which opening statement without scrolling or using the macro 'Edit.GotoBrace' several times. This tool provides a function which inserts comments after the closing brace automatically. The code snippet above would look like this:

Braces with comments

Comments are only inserted for closing braces of if, while, for and switch statements.

If you don't want to insert comments automatically while editing, you can turn off this function. If you just don't want those comments at specific places you have to move the caret either upwards (instead of downwards which happens if you press enter) or click with the mouse so that the caret doesn't go to the line below the closing brace. Comments are also not inserted when the opening brace is less than two lines above.

#region/#endregion for C++

VS.NET introduced to possibility to outline portions of text in the code editor. That's a very useful feature wthat helps navigating through big bunches of code. But the outlined sections are not saved between sessions. VB and C# provide keywords to outline sections. In VB its '#Region' and '#End Region', in C# its '#region' and '#endregion'. Only for C++ MS didn't provide such keywords (at least I haven't found them yet). With this tool you can now enable that feature for C++ too. To prevent compiler errors for those who have not installed this tool I used '//#region' and '//#endregion' as the keywords. With the comment lines before the compiler won't complain. Use those keywords like this:

outlined sections

Whenever you open a document with such keywords the tool will automatically create outlining sections. The section are also created when you type the '//#endregion' keyword and a matching '//#region' is found. As you can see, you can easily nest the sections. The code above would then look like this:

outlined sections

outlined sections

This function can't be deactivated. If you don't want it, simply don't use those keywords :)

Search the web

These two small addons perform a simple web site search either in the google groups or on CP. Select a piece of text in the code editor, right click to pop up the menu and then select where to search for the selected text. That's all. The search results will be opened inside VS.NET.

right click menu

Install

To install the tools, just double-click the *.msi file and follow the instructions. If the tools are not automatically activated the next time you start the IDE, then please activate them under Tools->Add-In Manager. Make sure you select both the addin and the box 'startup'.

All additional files needed for the tools are also packed in the installer, including Doxygen and the dot files. So you don't have to grab them separately from the web.

Source

Full source code is provided with these tools. The addin is written in VB.NET cause first there was just one simple tool that I wanted immediately - and VB is good enough for that. Then the tool grew and I added more functions. So the code is surely not the best example for good programming (no plan, no structure -> chaos). But maybe it might still be of interest for those who want to write their own addins. It shows a way to create submenus and how to add a toolbar.

Revision History

24.06.03
  • fixed bug in Doxygen part: the path to the binaries weren't enclosed in ""
  • made necessary changes to make the addin work with VS.NET2003 (projectitems are now recursive!)
  • updated the Doxygen binaries to the newest version
  • the dialogs are now centered to the IDE
18.04.03
  • fixed some bugs in the }EndOf function
  • added template files for doxygen comments
  • fixed bug in the graph functions if the solution contained "misc" files
  • Doxygen 1.3 is now included
  • removed the toolbar - it slowed the editor down
  • for most commands disabled the check for project type (C++, C#, VB, ...) - if you use a function for a project type for what it isn't designed it just won't work...
04.10.02
  • enabled }EndOf and the solution statistics also for C# projects
21.9.02
  • fixed a bug in the }EndOf tool
  • fixed bug where Doxygen couldn't be started when a file was in the Solution->Misc folder
  • added possibility to run Doxygen for single projects (right click menu in solution explorer)
  • included newest Doxygen and Dot version
  • added a proper uninstaller. The uninstaller now deletes all added commands.
7.9.02
  • fixed a bug reported by Darren Schroeder
8.8.02
  • removed forgotten test code which caused annoying behaviour
  • made sure that for WinHelp output (Doxygen) also html output is selected
10.8.02
  • fixed a bug reported by Jeff Combs: now the addin is only loaded when the IDE is started (the IDE is NOT started when devenv is called with /build, /clean or /deploy command line switches!)
12.8.02
  • Run Doxygen now includes not only project directories but all directories of the project files.
  • The Toolbar can now be altered and the altered state is saved by the IDE
  • Uninstalling now works better: the toolbar is gone after the second start of the IDE after uninstalling without modifying the source.
posted @ 2007-08-27 01:19 true 阅读(642) | 评论 (1)编辑 收藏

开源数据库概览

开源世界真是太奇妙了,虽然不排除卑鄙无耻的直接盗用并贯为自己的产品,但开源可以无私到随便你怎样用。

接触开源有很长的一段时间了,先是学习别人的,然后还参与了开源,在sf.net上,我主持和参与了数个开源项目,当然,都不是大型的项目,只是尝试一下。

我所关注的开源项目方面很多,每方面都有很多优秀的作品,我将会在接下来的系列随笔中介绍,这次介绍数据库。

这个星球上的数据库实在不胜枚举,这里只列一些我接触过的常见的。

可以稍微夸张点说,有交互的应用,起码得用一下数据保存,即便是自定义结构的数据保存,还是最常见的INI、XML等,都可以算是“数据库”,真正点的,如DBase系列、FoxBase、FoxPro、MSAccess、InterBase、MS SQL Server、Oracle、DB2等,这些是商业化的数据库,前面几个只能算是数据库,后面几个是RMDBS(关系型数据库管理系统)。

对应商业化的,有开源的:SQLiteSimpleSQLBerkely DBMinosseFirebird( 前身是是Borland公司的InterBase)、PostgreSQLMySQL等。

SQLite:大家可以看我的SQLite系列随笔,C编写的,可以跨操作平台,支持大部分ANSI SQL 92,它是嵌入式的轻量级关系形数据库引擎,只需要一个DLL,体积为250k,数据库也只是一个文件,零配置,便可工作。既然开源,你甚至可以把它嵌入你的程序中。核心开发人员只有一个,最近加入了另外一个,也就是2个人而已,实在佩服,目前发展到3.1.0,相当高效稳定,有开源驱动在sourceforge.net上有其ADO.NET Data Provider for SQLite :https://sourceforge.net/projects/adodotnetsqlite/

SimpleSQL:相对SQLite要大几倍,但也是轻量级的,功能稍微强大一点,C++编写,有OLE、Java等版本。

Berkely DB:C++编写的大型关系型数据库系统,还额外地支持XML(把XML当成数据库),号称2百万的安装量,MySQL也只不过号称5百万安装量而已,跨平台。

Minosse:纯C#编写的大型关系型数据库系统,理想是超越MS SQL Server!最新版本:0.2.0,真难得,纯Java写的看得多了,纯C#的,不是移植别人的,还是第一个,佩服作者:包含C/S和嵌入式版本,并可跨越大部分平台,因为它不用Windows的东西,可以在Mono下编译。

Firebird:这个东西太牛了,目前有1.5稳定版本已经拥有大量特性,完全支持ANSI SQL92、98等,一些超酷的特性让人疯狂(1.0特性1.5特性从这里开始研究),主要开发人员是一个俄罗斯人,目前开发队伍已经扩大到近100人,有3种模式,单机独立,典型C/S,超级服务器。2.0版本和3.0版本将在近期推出,看完其路线图(2.0、3.0)你就会疯掉。有.NET驱动,目前是1.7beta版。主要特性: 
    ◆A.C.I.D; 
    ◆MGA(任何版本的引擎都可以处理同一数据库记录); 
    ◆PSQL(存储过程)超级强大,ms sql相对的太次,它啥都能在服务器端实现并推送到客户端成为强大的报表,存储过程; 
    ◆触发器都可以在客户端获取监控追踪; 
    ◆自动只读模式; 
    ◆创新的事务保证绝对不会出错; 
    ◆24*7运行中仍然可以随时备份数据库; 
    ◆统一触发器:任何操作都可以让某表唯一的触发器来总控; 
    ◆大部分语言都可以写plug-in,并直接在存储过程中调用函数; 
    ◆c->c++,更加少的代码但更加快的速度; 
    ◆3种运行模式,甚至可以嵌入式; 
    ◆主流语言都可以调用它; 
    ◆动态sql执行; 
    ◆事务保存点;

PostgreSQL:POSTGRES数据库的后开源版本,号称拥有任何其他数据库没有的大量新特性,似乎目标是要做超大型的OO关系型数据库系统,目前已经发展到8.0,有.NET驱动中文官方网站有详细介绍。

MySQL:这个,不用说了吧?号称全球最受欢迎的开源数据库,但让我奇怪的是,PostgreSQL都有简体中文的支持:包括内核、管理工具、QA等等,在最新版本MySQL中,我却没有发现... ,有.NET驱动,其中MySQL Connector/Net就是原来在sf.net上的ByteFX.Data项目,作者已经加入了MySQL团队,参看《感慨 20 之开源的前途/钱图?(1数据库)》。
    
    网友评论
RunEverywhere:   纯Java写的数据库- -
  
  
  
  纯Java数据库包括:
  Informix, Cloudscape(也就是Apache Derby数据库),JDataStore(Borland公司),HSQLDB, db4o, PointBase(Oracle创始人开发),
  
  Berkeley DB Java Edition 2.0 开源数据库等等。谁有证据证明Oracle和DB2中Java使用的比例请告知。只知Oracle和DB2中有大量的.class文件,但不知是否有C/C++开发的部分,毕竟java也能编译成.exe和.dll文件。
  
  Oracle数据库(使用了Java开发,但不知是否是纯Java)
  www.oracle.com
  
  
  DB2数据库(使用了Java开发,但不知是否是纯Java):
  www-306.ibm.com/software/data/db2/
  
  Informix数据库
  
  IBM 在 2001 年七月初購併 Informix,將Informix 轉換為以Java 語言開發的環境之外,並採納 Informix
  的資料複製功能,提升 DB2 災難復原與資料複製的能力
  IBM 每年投資十億美元於資料庫管理軟體的研發工作,致力於強化資訊管理軟體解決方案的技術優勢與產品效能,去 ( 2003 ) 年並取得超過
  
  230 項相關專利權;又於日前捐出價值超過八千五百萬美元的 Java 資料庫軟體 Cloudscape 給 Apache
  
  
  http://www.ibm.com/news/tw/2004/11/tw_zh_20041119_linux.html
  Apache Derby 是一种用 100% 纯 Java 编写的关系数据库。该项目最初被称作 Cloudscape™,IBM 于 2004 年 8 月将它捐献给了 Apache 基金组织
  http://www-128.ibm.com/developerworks/cn/db2/library/techarticles/dm-0505gibson/?ca=dwcn-newsletter-db2
  
  
  Cloudscape 开源数据库
  
  於日前捐出價值超過八千五百萬美元的 Java 資料庫軟體 Cloudscape 給 Apache
  
  http://www.ibm.com/news/tw/2004/11/tw_zh_20041119_linux.html
  
  
  
  JDataStore数据库
  
  Borland公司出品:
  www.borland.com/us/products/jdatastore/
  
  
  HSQLDB开源数据库
  
  http://hsqldb.sf.net
  
  
  
  Berkeley DB Java Edition 2.0 开源数据库
  
  http://www.sleepycat.com/
  
  
  db4o开源数据库
  www.db4o.com/
  
  
  
  
  
  
  还有一些Java数据库:
  
  在全球最大的java开发者杂志上的一份对最受欢迎的Java数据库的调查:
  
  Best Enterprise Database:
  
   No Nominee
   Berkeley DB Java Edition Sleepycat Software
   Birdstep RDM Embedded 7.1 Birdstep Technology
   Daffodil DB Daffodil Software Ltd.
   db4o db4objects
   EAC MySQL Cluster Emic Networks
   HSQLDB HSQLDB Development Team
   IBM DB2 Universal Database IBM
   IBM Informix IDS v10 IBM
   JDataStore 7 High Availability Edition Borland Software
   ObjectDB for Java/JDO ObjectDB
   Oracle Database 10g Oracle Corporation
   Oracle Database Lite 10g Oracle Corporation
   PointBase Embedded PointBase / DataMirror Corp.
   Sybase Adaptive Server Enterprise (ASE) Sybase, Inc.
  
  
  http://jdj.sys-con.com/general/readerschoice.htm
  
  http://nuclearjava.blogchina.com/2006316.html (2005.06.26)

posted @ 2007-08-20 12:13 true 阅读(1077) | 评论 (0)编辑 收藏

仅列出标题
共15页: First 7 8 9 10 11 12 13 14 15