以下是一个用户认证的程序,username,userPwd都是要在数据库中查询的,使用ado
STDMETHODIMP CUserLogin::IsUserValid(BSTR *userName, BSTR *userPwd, BOOL *result)
{
// TODO: Add your implementation code here
VARIANT id;
CoInitialize(NULL);
char sqltxt[512];
try
{
sprintf(sqltxt,"select * from login where userName='%s' and userPwd='%s' ",(LPCSTR )userName,(LPCSTR )userPwd);
//上面这句话始终有问题
_RecordsetPtr pMyRecSet(__uuidof(Recordset));
pMyRecSet->Open(sqltxt,"DSN=LogDB;UID=sa;PWD=",adOpenStatic,adLockOptimistic,0);
if (pMyRecSet->adoEOF==VARIANT_FALSE)
*result=TRUE;
else
*result=FALSE;
pMyRecSet->Close(); }
catch(_com_error e)
{}
CoUninitialize();
return S_OK;
}sprintf那句始终有问题,我用sqlserver的事件探查器,实际上%s对应的BSTR是乱码
select * from login where userName=''?'' and userPwd=''漉''请教一下各位朋友,怎么修改一下可以正常运行?

解决方案 »

  1.   

    USES_CONVERSION;
    sprintf(sqltxt,"select * from login where userName='%s' and userPwd='%s' ",OLE2CT(*userName),OLE2CT(*userPwd));
      

  2.   

    感觉在COM中直接这样定义char sqltxt[512];并用sprintf操作这个sqltxt好像有问题,
    呵呵,请朋友们指教~!
      

  3.   

    to  ColderRain(我想买电脑) :
    OLE2CT(*userName) 您这样强制转换有错
    '=' : cannot convert from 'unsigned short *' to 'int'to gjd111686(数字金刚) :
    用LPCTSTR转换也有错.与LPCSTR差不多,执行的SQL中也是乱码.请各位朋友指教~!
      

  4.   

    sprintf(sqltxt,"select * from login where userName='%s' and userPwd='%s' ",(LPCSTR )(_bstr_t)userName,(LPCSTR )(_bstr_t)userPwd);
      

  5.   

    sorry:)sprintf(sqltxt,"select * from login where userName='%s' and userPwd='%s' ",(LPCSTR )(_bstr_t)*userName,(LPCSTR )(_bstr_t)*userPwd);
      

  6.   

    实际上就是把BSTR转成char*.
    这个有很多种办法,可以参见下面这个帖子:
    http://expert.csdn.net/Expert/TopicView1.asp?id=2715859