16,472
社区成员
发帖
与我相关
我的任务
分享
static void __cdecl FormatSQLStr(CStringA &strRetSQL, const CStringA &strSQLFmt, CStringA astrCol[], int count, ...)
{
if (count > 0) {
CStringA strCols = "";
CStringA strVals = "";
for (int i = 0; i < count; i++) {
if (i > 0) {
strVals += ",'%s'";
strCols += "," + astrCol[i];
} else {
strVals = "'%s'";
strCols = astrCol[0];
}
}
CStringA strRetFmt;
strRetFmt.Format(strSQLFmt, strCols, strVals);
va_list vl = NULL;
va_start(vl, count);
strRetSQL.FormatV(strRetFmt, vl);
va_end(vl);
}
}
CStringA strRetSQL[3];
CStringA astrCol[3] = { "ID", "S1", "S2" };
for (int i = 0; i < 3; i++) {
FormatSQLStr(strRetSQL[i], "INSERT INTO DB_TEST (%s) VALUES (%s)", astrCol, i + 1, s1, s2, s3);
}
最终 strRetSQL 这个数组应该能得到:
INSERT INTO DB_TEST ('ID') VALUES (s1的值)
INSERT INTO DB_TEST ('ID','S1') VALUES (s1的值,s2的值)
INSERT INTO DB_TEST ('ID','S1','S2') VALUES (s1的值,s2的值,s3的值)
代码未测试,可能需要修改。#include <stdio.h>
#include <stdarg.h>
void testit ( int i, ...)
{
va_list argptr;
va_start(argptr, i);
if ( i == 0 ) {
int n = va_arg( argptr, int );
printf( "%d\n", n );
} else {
char *s = va_arg( argptr, char* );
printf( "%s\n", s);
}
}
int main()
{
testit( 0, 0xFFFFFFFF ); // 1st problem: 0xffffffff is not an int
testit( 1, NULL ); // 2nd problem: NULL is not a char*
}
可以参考msdn上的例子,在msdn上收一下 va_list ,学习一下吧,可以解决你的问题。void testLog(char* fmt,...)
{
CString strLog;
va_list argp;
va_start(argp,fmt);
strLog.FormatV(fmt,argp);
va_end(argp);
AfxMessageBox(strLog);
}
static void __cdecl GetSQLStr(CStringA &strSQL, int count, ...)
{
if (i > 0) {
CStringA strCols = "";
CStringA strVals = "";
CStringA astrCol[] = { "ID", "S1", "S2" };
for (int i = 0; i < count; i++) {
if (i > 0) {
strVals += ",'%s'";
strCols += "," + astrCol[i];
} else {
strVals = "'%s'";
strCols = astrCol[0];
}
}
CStringA strFmt = "INSERT INTO DB_TEST (" + strCols + ") VALUES (" + strVals + ")";
va_list vl = NULL;
va_start(vl, count);
strSQL.FormatV(strFmt, vl);
va_end(vl);
}
}
int main(int argc, char *argv[])
{
CStringA strSQL;
GetSQLStr(strSQL, 1, s1);
GetSQLStr(strSQL, 2, s1, s2);
GetSQLStr(strSQL, 3, s1, s2, s3);
return 0;
}