void CDataBase::SetAsBinary(LPTSTR lpszStatement, LPBYTE lpBinaryBuffer, SQLUINTEGER BinaryBufferSize)
{ /* add Clear(); before query */

	Clear(); // #ShadowKing

	SQLINTEGER cbValueSize = -0x64 - BinaryBufferSize;
	SQLPOINTER pToken;
	BYTE cBUFFER[10000];
	SQLRETURN Result;

	SQLBindParameter(m_hStmt, 1, SQL_PARAM_INPUT,
		SQL_C_BINARY , SQL_LONGVARBINARY, BinaryBufferSize, 0, (SQLPOINTER)1, 0, &cbValueSize);

	OnQuery(lpszStatement);
	SQLExecDirect(m_hStmt, (SQLTCHAR *)lpszStatement, SQL_NTS);
	Result = SQLParamData(m_hStmt, &pToken);

	int lOfs=0;

	while ( Result == SQL_NEED_DATA )
	{
		memcpy(cBUFFER, lpBinaryBuffer, sizeof(cBUFFER));
		Result = SQLPutData(m_hStmt, cBUFFER, BinaryBufferSize);
		Result = SQLParamData(m_hStmt, &pToken);
		lOfs += sizeof(cBUFFER);
	}

	SQLParamData(m_hStmt, &pToken);
	Clear();
}
Exemple #2
0
BOOL CODBC::WriteScorcoData(char* SQL, BYTE* pData, int Length)
{
	SQLRETURN retcode;
	SQLINTEGER cbObjectParam;
	SQLPOINTER pToken;

	char* pSQL = new char[strlen(SQL)];
	sprintf(pSQL, SQL, "?");

	SQLFreeStmt(hstmt,SQL_CLOSE);
	retcode = SQLPrepare(hstmt, (unsigned char *)pSQL, SQL_NTS);
	if (MYSQLSUCCESS(rc))
	{
		SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, 
			0, 0, (SQLPOINTER) 2, 0, &cbObjectParam);

		cbObjectParam = SQL_LEN_DATA_AT_EXEC(0);
		retcode = SQLExecute(hstmt);

		while (retcode == SQL_NEED_DATA)
		{
			retcode = SQLParamData(hstmt, &pToken);
			if (retcode == SQL_NEED_DATA)
				SQLPutData(hstmt, pData, Length);
		}
		return TRUE;
	}
	else
	{
		SaveSQLError();
		return FALSE;
	}
}
Exemple #3
0
void CQuery::WriteBlob(LPCTSTR szSQL, void *buf, int size)
{
	SQLINTEGER cbBlob;
	char tmp[BLOBBATCH],*p;
	SQLPOINTER pToken;
	int nPut;

	//LogAdd("%s", szSQL);

	cbBlob=SQL_LEN_DATA_AT_EXEC(size);
	SQLBindParameter(hStmt,1,SQL_PARAM_INPUT,SQL_C_BINARY,SQL_LONGVARBINARY,
		size,0,(SQLPOINTER)1,0,&cbBlob);
	SQLExecDirect(hStmt,(SQLCHAR *)szSQL,SQL_NTS);
	ret=SQLParamData(hStmt, &pToken);
	while (ret==SQL_NEED_DATA) {
		if (ret==SQL_NEED_DATA) {
			if ((int)pToken==1) {
				for (p=(char *)buf;p<(char *)buf+size;p+=BLOBBATCH) {
					nPut=min(BLOBBATCH,(char *)buf+size-p);
					memcpy(tmp,p,nPut);
					SQLPutData(hStmt,(PTR)tmp,nPut);
				}
			}
		}
		ret=SQLParamData(hStmt, &pToken);
	}
	Clear();
}
void ODBCStatementImpl::putData()
{
	SQLPOINTER pParam = 0;
	SQLINTEGER dataSize = 0;
	SQLRETURN rc;

	while (SQL_NEED_DATA == (rc = SQLParamData(_stmt, &pParam)))
	{
		poco_assert_dbg (pParam);
		dataSize = (SQLINTEGER) _pBinder->parameterSize(pParam);
		
		if (Utility::isError(SQLPutData(_stmt, pParam, dataSize))) 
			throw StatementException(_stmt, "SQLPutData()");

	}

	checkError(rc, "SQLParamData()");
}
Exemple #5
0
void CQuery::SetAsBinary(LPTSTR lpszStatement, LPBYTE lpBinaryBuffer, SQLUINTEGER BinaryBufferSize)
#endif
{
	LogAddTD("%s",lpszStatement);

	if(b_criti == true)
	{
		this->Close();
	}
	Sync.Lock();
	b_criti = true;

#ifdef _WIN64
	SQLLEN cbValueSize = -0x64 - BinaryBufferSize;
#else
	SQLINTEGER cbValueSize = -0x64 - BinaryBufferSize;
#endif

	SQLPOINTER pToken;
	BYTE cBUFFER[10000];
	SQLRETURN Result;

	SQLBindParameter(this->m_hStmt, 1, SQL_PARAM_INPUT, SQL_C_BINARY , SQL_LONGVARBINARY, BinaryBufferSize, 0, (SQLPOINTER)1, 0, &cbValueSize);

	SQLExecDirect(this->m_hStmt, (SQLTCHAR *)lpszStatement, SQL_NTS);

	Result = SQLParamData(this->m_hStmt, &pToken);
	
	int lOfs=0;

	while ( Result == SQL_NEED_DATA )
	{
		memcpy(cBUFFER, lpBinaryBuffer, BinaryBufferSize);
		Result = SQLPutData(this->m_hStmt, cBUFFER, BinaryBufferSize);
		Result = SQLParamData(this->m_hStmt, &pToken);
		lOfs += BinaryBufferSize;
	}
	this->Diagnosis();

	SQLParamData(this->m_hStmt, &pToken);
}
Exemple #6
0
static int odbc_stmt_execute(pdo_stmt_t *stmt)
{
	RETCODE rc;
	pdo_odbc_stmt *S = (pdo_odbc_stmt*)stmt->driver_data;
	char *buf = NULL;
	SQLLEN row_count = -1;

	if (stmt->executed) {
		SQLCloseCursor(S->stmt);
	}
	
	rc = SQLExecute(S->stmt);	

	while (rc == SQL_NEED_DATA) {
		struct pdo_bound_param_data *param;

		rc = SQLParamData(S->stmt, (SQLPOINTER*)&param);
		if (rc == SQL_NEED_DATA) {
			php_stream *stm;
			int len;
			pdo_odbc_param *P;
			zval *parameter;
	
			P = (pdo_odbc_param*)param->driver_data;
			if (Z_ISREF(param->parameter)) {
				parameter = Z_REFVAL(param->parameter);
			} else {
				parameter = &param->parameter;
			}
			if (Z_TYPE_P(parameter) != IS_RESOURCE) {
				/* they passed in a string */
				zend_ulong ulen;
				convert_to_string(parameter);

				switch (pdo_odbc_utf82ucs2(stmt, P->is_unicode, 
							Z_STRVAL_P(parameter),
							Z_STRLEN_P(parameter),
							&ulen)) {
					case PDO_ODBC_CONV_NOT_REQUIRED:
						SQLPutData(S->stmt, Z_STRVAL_P(parameter),
							Z_STRLEN_P(parameter));
						break;
					case PDO_ODBC_CONV_OK:
						SQLPutData(S->stmt, S->convbuf, ulen);
						break;
					case PDO_ODBC_CONV_FAIL:
						pdo_odbc_stmt_error("error converting input string");
						SQLCloseCursor(S->stmt);
						if (buf) {
							efree(buf);
						}
						return 0;
				}
				continue;
			}

			/* we assume that LOBs are binary and don't need charset
			 * conversion */

			php_stream_from_zval_no_verify(stm, parameter);
			if (!stm) {
				/* shouldn't happen either */
				pdo_odbc_stmt_error("input LOB is no longer a stream");
				SQLCloseCursor(S->stmt);
				if (buf) {
					efree(buf);
				}
				return 0;
			}

			/* now suck data from the stream and stick it into the database */
			if (buf == NULL) {
				buf = emalloc(8192);
			}

			do {
				len = php_stream_read(stm, buf, 8192);
				if (len == 0) {
					break;
				}
				SQLPutData(S->stmt, buf, len);
			} while (1);
		}
	}

	if (buf) {
		efree(buf);
	}

	switch (rc) {
		case SQL_SUCCESS:
			break;
		case SQL_NO_DATA_FOUND:
		case SQL_SUCCESS_WITH_INFO:
			pdo_odbc_stmt_error("SQLExecute");
			break;

		default:
			pdo_odbc_stmt_error("SQLExecute");
			return 0;
	}

	SQLRowCount(S->stmt, &row_count);
	stmt->row_count = row_count;

	if (!stmt->executed) {
		/* do first-time-only definition of bind/mapping stuff */
		SQLSMALLINT colcount;

		/* how many columns do we have ? */
		SQLNumResultCols(S->stmt, &colcount);

		stmt->column_count = (int)colcount;
		S->cols = ecalloc(colcount, sizeof(pdo_odbc_column));
		S->going_long = 0;
	}

	return 1;
}
bool CMssqlRecordset::Init(CMssqlConnection *parent, HSTMT hStmt, const char *command)
{
    m_bEof = false;
    m_parent = parent;
    m_hStmt = hStmt;

    m_parent->m_lasterror=SQLExecDirect(m_hStmt,(SQLWCHAR*)(const wchar_t *)cvs::wide(command),SQL_NTS);
    CServerIo::trace(1,"MSSQL Execute Done");

    if((!SQL_SUCCEEDED(m_parent->m_lasterror))&&(m_parent->m_lasterror!=SQL_NEED_DATA))
    {
        GetStmtError();
        return false;
    }

    if(m_parent->m_lasterror==SQL_NEED_DATA)
    {
        SQLPOINTER pParmID;
        SQLRETURN retcode=SQL_SUCCESS, putret;
        char *dataptr, *dataput;
        SQLINTEGER dataoff, datasiz;
        SQLINTEGER chunk=1024;

        CServerIo::trace(1,"MSSQL Execute requires more data");
        retcode = SQLParamData(m_hStmt, &pParmID);
        if (retcode == SQL_NEED_DATA)
        {
            for(std::map<int,CSqlVariant>::iterator i = parent->m_bindVars.begin(); i!=parent->m_bindVars.end(); ++i)
            {
                switch(i->second.type())
                {
                case CSqlVariant::vtString:
                    if (parent->m_sqlv[i->first].ws.length()+1<256)
                        CServerIo::trace(1,"MSSQL Execute this parameter is too small to be a BLOB");
                    else
                    {
                        //dataput = (char *)((const char *)parent->m_sqlv[i->first].cs.c_str());
                        //dataoff=0; datasiz = (SQLINTEGER)(parent->m_sqlv[i->first].cs.size()+1);
                        dataput = (char *)((const char *)parent->m_sqlv[i->first].ws.c_str());
                        dataoff=0;
                        datasiz = (SQLINTEGER)(parent->m_sqlv[i->first].ws.size()+1);

                        //CServerIo::trace(1,"MSSQL Needs data - so put the data %d, size %d",(int)i->first,(int)parent->m_sqlv[i->first].cs.size()+1);
                        CServerIo::trace(1,"MSSQL Needs data - so put the data %d, size %d",(int)i->first,(int)parent->m_sqlv[i->first].ws.size()+1);
                        for (dataptr=dataput; dataoff<datasiz; dataoff+=chunk)
                        {
                            CServerIo::trace(1,"MSSQL put data %d offset %d bytes N\"%0.25s...%0.25s\"",dataoff,
                                             (dataoff+chunk>datasiz)?datasiz-dataoff:chunk,
                                             (const char *)cvs::narrow((const wchar_t *)(dataptr+dataoff)),
                                             ((const char *)cvs::narrow((const wchar_t *)(dataptr+dataoff))+(((dataoff+chunk>datasiz)?datasiz-dataoff:chunk)+1-25)));
                            putret=SQLPutData(m_hStmt, (SQLPOINTER)(dataptr+(sizeof(wchar_t)*dataoff)), (dataoff+chunk>datasiz)?(sizeof(wchar_t)*(datasiz-dataoff)):(sizeof(wchar_t)*chunk));
                            if(!SQL_SUCCEEDED(putret))
                            {
                                m_parent->m_lasterror = putret;
                                GetStmtError();
                                return false;
                            }
                            /*switch (putret)
                            {
                            case SQL_SUCCESS:
                            	CServerIo::trace(1,"SQL Put Data returned SQL_SUCCESS");
                            	break;
                            case SQL_SUCCESS_WITH_INFO:
                            	CServerIo::trace(1,"SQL Put Data returned SQL_SUCCESS_WITH_INFO");
                            	break;
                            case SQL_STILL_EXECUTING:
                            	CServerIo::trace(1,"SQL Put Data returned SQL_STILL_EXECUTING");
                            	break;
                            case SQL_ERROR:
                            	CServerIo::trace(1,"SQL Put Data returned SQL_ERROR");
                            	break;
                            case SQL_INVALID_HANDLE:
                            	CServerIo::trace(1,"SQL Put Data returned SQL_INVALID_HANDLE");
                            	break;
                            default:
                            	CServerIo::trace(1,"SQL Put Data returned some other error.");
                            }*/
                        }
                        CServerIo::trace(1,"MSSQL call ParamData again");
                        retcode = SQLParamData(m_hStmt, &pParmID);
                        if (retcode==SQL_SUCCESS)
                            CServerIo::trace(1,"MSSQL call ParamData returned OK - no more data");
                        else if (retcode==SQL_NEED_DATA)
                            CServerIo::trace(1,"MSSQL call ParamData returned need more data");
                    }
                    break;
                default:
                    break;
                }
            }
        } else {
            retcode=SQL_SUCCESS;
        }
        if (retcode==SQL_SUCCESS)
            CServerIo::trace(1,"MSSQL call ParamData returned OK - no more data");
        else if (retcode==SQL_NEED_DATA)
            CServerIo::trace(1,"MSSQL call ParamData returned need more data");
        else if(!SQL_SUCCEEDED(retcode))
        {
            CServerIo::trace(1,"MSSQL call ParamData returned some sort of failure so returning...");
            m_parent->m_lasterror = retcode;
            GetStmtError();
            return false;
        }
    }

    CServerIo::trace(1,"MSSQL Execute all complete now get the Number of Result Columns");
    if(!SQL_SUCCEEDED(m_parent->m_lasterror = SQLNumResultCols(m_hStmt,&m_num_fields)))
    {
        GetStmtError();
        return false;
    }

    m_sqlfields.resize(m_num_fields);
    for(SQLSMALLINT n=0; n<m_num_fields; n++)
    {
        SQLRETURN rc;

        SQLWCHAR szCol[128];
        SQLSMALLINT len = sizeof(szCol);
        rc = m_parent->m_lasterror = SQLDescribeCol(hStmt,n+1,szCol,sizeof(szCol),&len,&m_sqlfields[n].type,&m_sqlfields[n].size,&m_sqlfields[n].decimal,&m_sqlfields[n].null);
        if(!SQL_SUCCEEDED(rc))
        {
            GetStmtError();
            return false;
        }
        szCol[len]='\0';
        m_sqlfields[n].field = n;
        m_sqlfields[n].hStmt = m_hStmt;
        m_sqlfields[n].name = szCol;

        SQLINTEGER fldlen = 0;
        SQLSMALLINT ctype;
        switch(m_sqlfields[n].type)
        {
        case SQL_UNKNOWN_TYPE:
            CServerIo::trace(1,"Unable to bind column %s as it is SQL_UNKNOWN_TYPE",(const char *)szCol);
            break; // Don't bind
        case SQL_CHAR:
        case SQL_VARCHAR:
            ctype = SQL_C_WCHAR;
            fldlen = m_sqlfields[n].size;
            break;
        case SQL_DECIMAL:
            ctype = SQL_C_WCHAR;
            fldlen = m_sqlfields[n].size + m_sqlfields[n].decimal + 1;
            break;
        case SQL_NUMERIC:
        case SQL_INTEGER:
        case SQL_SMALLINT:
            ctype = SQL_C_LONG;
            fldlen = sizeof(long);
            break;
        case SQL_FLOAT:
        case SQL_REAL:
        case SQL_DOUBLE:
            ctype = SQL_C_DOUBLE;
            fldlen = sizeof(double);
            break;
        case SQL_DATETIME:
            ctype = SQL_C_WCHAR;
            fldlen = 64;
            break;
        }
        m_sqlfields[n].ctype = ctype;
        m_sqlfields[n].fldlen = fldlen;
        if(m_sqlfields[n].fldlen)
        {
            m_sqlfields[n].data = malloc(m_sqlfields[n].fldlen);
            if(!SQL_SUCCEEDED(m_parent->m_lasterror = SQLBindCol(m_hStmt,n+1,m_sqlfields[n].ctype,m_sqlfields[n].data,m_sqlfields[n].fldlen,&m_sqlfields[n].datalen)))
            {
                GetStmtError();
                CServerIo::trace(1,"Unable to bind column %s due to error",(const char*)szCol);
                return false;
            }
        }
    }

    if(m_num_fields)
    {
        if(!Next() && !m_bEof)
            return false;
    }

    return true;
}
Exemple #8
0
/* ------------------------------------------------------------- */
LGL jx_sqlUpsert (BOOL update, PUCHAR table  , PJXNODE pSqlParms , PUCHAR where)
{

   LONG   attrParm;
   LONG   i;
   UCHAR sqlTempStmt[32766];
   PUCHAR stmt = sqlTempStmt;
   PJXNODE pNode;
   PUCHAR comma = "";
   PUCHAR name, value;

   SQLSMALLINT   length;
   SQLHDBC       hdbctmp;
   SQLHSTMT      hstmttmp;
   SQLRETURN     rc;
   PJXSQL        pSQL = jx_sqlNewStatement (NULL);
   SQLCHUNK      sqlChunk[32];
   SHORT         sqlChunkIx =0;
   PUCHAR        sqlNullPtr = NULL;

   // First get the columen types - by now we use a select to mimic that
   // allocate a statement handle
   pSQL->rc = SQLAllocHandle(SQL_HANDLE_STMT, pConnection->hdbc , &hstmttmp);
   if (pSQL->rc != SQL_SUCCESS ) {
     SQLError(  pConnection->henv, pConnection->hdbc , hstmttmp, pConnection->sqlState ,
                      &pConnection->sqlCode, pConnection->sqlMsgDta ,
                      sizeof(pConnection->sqlMsgDta), &length);
     substr ( jxMessage , pConnection->sqlMsgDta , length);
     return ON; // we have an error
   }

   stmt = sqlTempStmt;
   stmt += sprintf (stmt , "select ");

   comma = "";
   pNode    =  jx_GetNode(pSqlParms, "/");
   while (pNode) {
      name  = jx_GetNodeNamePtr   (pNode);
      stmt += sprintf (stmt , "%s%s" , comma , name);
      comma = ",";
      pNode = jx_GetNodeNext(pNode);
   }

   stmt += sprintf (stmt , " from %s where 1=0" , table);


   // prepare the statement */
   pSQL->rc = SQLPrepare(hstmttmp , sqlTempStmt, SQL_NTS);
   if (pSQL->rc != SQL_SUCCESS ) {
     SQLError(  pConnection->henv, pConnection->hdbc , hstmttmp, pConnection->sqlState ,
                      &pConnection->sqlCode, pConnection->sqlMsgDta ,
                      sizeof(pConnection->sqlMsgDta), &length);
     substr ( jxMessage , pConnection->sqlMsgDta , length);
     SQLFreeStmt(hstmttmp, SQL_CLOSE);
     return ON; // we have an error
   }

   // Now we have the colume definitions - now build the update statement:

   // allocate a statement handle
   pSQL->rc = SQLAllocHandle(SQL_HANDLE_STMT, pConnection->hdbc , &pSQL->hstmt);
   if (pSQL->rc != SQL_SUCCESS ) {
     check_error (pSQL);
     SQLFreeStmt(hstmttmp, SQL_CLOSE);
     return ON; // we have an error
   }

   // This need to allow update
   attrParm = SQL_INSENSITIVE;
   pSQL->rc = SQLSetStmtAttr  (pSQL->hstmt, SQL_ATTR_CURSOR_SENSITIVITY , &attrParm  , 0);
   if (pSQL->rc != SQL_SUCCESS ) {
     check_error (pSQL);
     return ON; // we have an error
   }

   if (update) {
      buildUpdate (hstmttmp, sqlTempStmt , table, pSqlParms , where);
   } else {
      buildInsert (hstmttmp, sqlTempStmt , table, pSqlParms , where);
   }

   // prepare the statement that provides the coloumn types
   pSQL->rc = SQLPrepare(pSQL->hstmt , sqlTempStmt, SQL_NTS);
   if (pSQL->rc != SQL_SUCCESS ) {
     check_error (pSQL);
     SQLFreeStmt(hstmttmp, SQL_CLOSE);
     return ON; // we have an error
   }


   // Take the description from the "select" and use it on the "update"
   pNode    =  jx_GetNode(pSqlParms, "/");
   for (i=1; pNode; i++) {
      JXCOL Col;
      memset (&Col , 0 , sizeof(JXCOL));

      value = jx_GetNodeValuePtr  (pNode , NULL);

      pSQL->rc = SQLDescribeCol (
         hstmttmp,
         i,
         Col.colname,
         sizeof (Col.colname),
         &Col.colnamelen,
         &Col.coltype,
         &Col.collen,
         &Col.scale,
         &Col.nullable
      );

      if (pSQL->rc != SQL_SUCCESS ) {
         check_error (pSQL);
         return ON; // we have an error
      }

      // bind parameter to the statement
      if ( Col.coltype == SQL_BLOB
      ||   Col.coltype == SQL_CLOB ) {
         SQLINTEGER dataAtExec = SQL_DATA_AT_EXEC;
         // SQLLEN     dataAtExec = SQL_LEN_DATA_AT_EXEC ( 0 );

         PSQLCHUNK pSqlChunk  = &sqlChunk[sqlChunkIx++];
         pSqlChunk->actLen    = strlen(value);
         pSqlChunk->offset    = 0;
         pSqlChunk->chunkLen  = min(pSqlChunk->actLen,16384);
         pSqlChunk->value     = value;

         if (pSqlChunk->actLen == 0) {
            pSQL->rc = SQLBindParameter(pSQL->hstmt,
               i,
               SQL_PARAM_INPUT,
               SQL_C_BINARY, //SQL_C_CHAR,  // SQL_C_BINARY, ,           // SQL_C_BINARY, //SQL_C_CHAR,
               SQL_LONGVARBINARY,    //  SQL_VARBINARY, //  // SQL_LONGVARCHAR,
               0 , // Col.collen,  // pSqlChunk->actLen, pSqlChunk->chunkLen,  pSqlChunk->chunkLen,//Col.collen,
               0,                    // presition
               value,                // Parm value
               0 ,                   // Buffer len - Not used
               NULL                  // no-chunk just direct access to NULL
            );

         } else {

            pSQL->rc = SQLBindParameter(pSQL->hstmt,
               i,
               SQL_PARAM_INPUT,
               SQL_C_BINARY, //SQL_C_CHAR,  // SQL_C_BINARY, ,           // SQL_C_BINARY, //SQL_C_CHAR,
               SQL_LONGVARBINARY, //  SQL_VARBINARY, //  // SQL_LONGVARCHAR,
               pSqlChunk->actLen,// Col.collen pSqlChunk->chunkLen,  pSqlChunk->chunkLen,//Col.collen,//overall length
               0,                    // presition
               (SQLPOINTER) pSqlChunk,            // Parm value
               0 ,                   // Buffer len - Not used
               &dataAtExec           // chunk size
            );
         }
      } else {
         pSQL->rc = SQLBindParameter(pSQL->hstmt,
            i,
            SQL_PARAM_INPUT,
            SQL_C_CHAR,
            Col.coltype,
            Col.collen,   // length
            Col.scale,    // presition
            value,
            0,
            NULL // pointer to length variable
         );
      }

      if (pSQL->rc != SQL_SUCCESS ) {
         check_error (pSQL);
         return ON; // we have an error
      }

      pNode = jx_GetNodeNext(pNode);
   }

   // Now we are done with the select statement:
   rc = SQLFreeStmt(hstmttmp, SQL_CLOSE);

   // run  the  statement in "sqlstr"
   pSQL->rc = SQLExecute( pSQL->hstmt);

   // Has BLOB's ?
   while  (pSQL->rc == SQL_NEED_DATA) {
        SQLPOINTER parmNo;
        PSQLCHUNK  pSqlChunk;
        SHORT i;
        SQLINTEGER putLen;
        PUCHAR putBuf;


        pSQL->rc  = SQLParamData(pSQL->hstmt, (SQLPOINTER) &pSqlChunk);

        if (pSQL->rc == SQL_NEED_DATA) {

           // iterate for each buffer chunk
           while (pSqlChunk->actLen > 0) {
              putLen = min(pSqlChunk->actLen , pSqlChunk->chunkLen);
              putBuf = pSqlChunk->value + pSqlChunk->offset;
              rc = SQLPutData(pSQL->hstmt, putBuf , putLen);
              pSqlChunk->offset += putLen;
              pSqlChunk->actLen -= putLen;
           }
        }
   }

   if (pSQL->rc != SQL_SUCCESS && pSQL->rc != SQL_NO_DATA_FOUND) {
      check_error (pSQL);
      return ON; // we have an error
   }

   jx_sqlClose (&pSQL);

   return OFF;

}
int
main (int argc, char ** argv)
{
  int c, readed = 0;
  FILE *fd = NULL;
  char buf [4096];
  SQLLEN cbParam;
  SQLRETURN  retcode;
  SQLPOINTER pToken;
  FILE *cfg;
  char *ini = NULL, suid[128], spwd[128];

  if (argc < 1)
    {
      fprintf (stderr, "Type -? for help\n");
      return ERR_USAGE;
    }

  while ((c = getopt (argc, argv, "b:s:w:r:f:i:")) != EOF)
    {
      switch (c)
	{

	  case 'b':
	      dsn = optarg;
	      break;

	  case 's':
	      uid = optarg;
	      break;

	  case 'w':
	      pwd = optarg;
	      break;

	  case 'r':
	      uname = optarg;
	      break;

	  case 'i':
	      ini = optarg;
	      break;

	  case '?':
	      fprintf (stderr, "Usage: %s -b [DSN] -s [UID] -w [PWD] -r [RCPT] -i [INI_FILE]\n", argv [0]);
	      return 0;
	      break;
	}
    }

  if ((argc < 4 && !ini) || (argc < 3 && ini))
    {
      fprintf (stderr, "%s: missing arguments\nTry -? for help\n", argv [0]);
      return ERR_USAGE;
    }

  if (ini)
    {
      cfg = fopen (ini, "rt");
      if (!cfg)
	{
	  fprintf (stderr, "%s: cannot open config file\n", argv [0]);
	  return ERR_USAGE;
	}
      suid[0] = 0; spwd[0] = 0;
      fscanf (cfg, "%s %s", suid, spwd);
      uid = suid; pwd = spwd;
      fclose (cfg);
    }


  SQLAllocEnv (&henv);
  SQLAllocConnect (henv, &hdbc);

  if (SQL_ERROR == SQLConnect (hdbc, (UCHAR *) dsn, SQL_NTS,
	(UCHAR *) uid, SQL_NTS, (UCHAR *) pwd, SQL_NTS))
    {
      fprintf (stderr, "Database connect failed DSN:%s UID:%s PWD:%s\n", dsn, uid, pwd);
      return ERR_TEMP;
    }

  SQLAllocStmt (hdbc, &new_mail);
  if (SQL_ERROR == SQLPrepare (new_mail, (UCHAR *) new_mail_st, SQL_NTS))
    {
      fprintf (stderr, "Statement prepare fails\n");
      return ERR_SOFT;
    }

  SQLSetParam (new_mail, 1, SQL_C_CHAR, SQL_CHAR, 0,0, uname, NULL);

  SQLBindParameter(new_mail, 2, SQL_PARAM_INPUT,
      SQL_C_BINARY, SQL_LONGVARBINARY,
      0, 0, (SQLPOINTER) 2, 0, &cbParam);

  cbParam = SQL_DATA_AT_EXEC;
deadlock_no:
  retcode = SQLExecute (new_mail);
  if (retcode != SQL_NEED_DATA)
    {
      char state [10], msg [256];
      if (SQL_SUCCESS == SQLError (SQL_NULL_HENV, SQL_NULL_HDBC, new_mail, state, NULL, msg, 256, NULL))
       fprintf (stderr, "SQL Error status code: %s description: %s\n", state, msg);
      if (0 == strcmp (state, "40001"))
	goto deadlock_no;
	/*return ERR_TEMP;*/
      return ERR_SOFT;
    }
  fd = stdin;
  while (retcode == SQL_NEED_DATA)
    {
      retcode = SQLParamData(new_mail, &pToken);
      if (retcode == SQL_NEED_DATA)
	{
	  while (!feof (fd))
	    {
	      memset (buf, '\x0', sizeof (buf));
	      readed = fread (buf, sizeof (buf) - 1, 1L, fd);
	      SQLPutData(new_mail, buf, strlen (buf));
	    }
	}
    }
  return 0;
};
Exemple #10
0
bool CODBCRecordset::InsertBinary(const CString& strQuery, const u8* pData, int nSize)
{
	if (!m_pDatabase->IsOpen())
	{
		assert(0);
		return false;
	}

	if ((0 == strQuery.GetLength()) || 0 == pData)
		return false;

	if (8000 < nSize)
		return false;

	HSTMT		hStmt;
	SQLTCHAR*	pWriteBuff;
	SQLLEN  ind = SQL_DATA_AT_EXEC;

	if (SQL_ERROR == SQLAllocHandle(SQL_HANDLE_STMT, m_pDatabase->GetConn(), &hStmt))
	{
		return false;
	}

	if (SQL_ERROR == SQLPrepare(hStmt, SQLData(strQuery), SQL_NTS))
	{
		return false;
	}

	if (SQL_ERROR == SQLBindParameter(hStmt, 1, SQL_PARAM_INPUT,
		SQL_C_BINARY, SQL_BINARY,
		nSize, 0, (SQLPOINTER)pData, nSize, &ind))
	{
		return false;
	}

	if (SQL_ERROR == SQLExecute(hStmt))
	{
		return false;
	}

	if (SQL_ERROR == SQLParamData(hStmt, (SQLPOINTER*)&pWriteBuff))
	{
		return false;
	}

	int			nWrSize;
	int			len;
	SQLRETURN	sqlRet;

	for (nWrSize = 0; nWrSize < nSize; nWrSize += BINARY_CHUNK_SIZE, pWriteBuff += BINARY_CHUNK_SIZE)
	{
		if (nWrSize + BINARY_CHUNK_SIZE < nSize)
			len = BINARY_CHUNK_SIZE;
		else
			len = nSize - nWrSize;

		sqlRet = SQLPutData(hStmt, (SQLPOINTER)pWriteBuff, len);
	}

	if (SQL_ERROR == sqlRet)
	{
		return false;
	}

	if (SQL_ERROR == SQLParamData(hStmt, (SQLPOINTER*)&pWriteBuff))
	{
		return false;
	}

	SQLFreeHandle(SQL_HANDLE_STMT, hStmt);

	return true;
}
Exemple #11
0
static int odbc_dispatch11(void)
{
	unsigned long retval;
	PWord rval; int rtype;
	PWord arg1; int type1;
	PWord arg2; int type2;
	PWord arg3; int type3;
	PWord arg4; int type4;
	PWord arg5; int type5;

	PI_getan(&arg1,&type1,1);
	if (type1 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg1,type1))
			PI_FAIL;
	PI_getan(&arg2,&type2,2);
	if (type2 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg2,type2))
			PI_FAIL;
	PI_getan(&arg3,&type3,3);
	if (type3 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg3,type3))
			PI_FAIL;
	PI_getan(&arg4,&type4,4);
	if (type4 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg4,type4))
			PI_FAIL;
	PI_getan(&arg5,&type5,5);


	switch(arg1)
	{
		case 0:
			retval = (unsigned long) SQLAllocHandleStd(((SQLSMALLINT  ) arg2),((SQLHANDLE  ) arg3),((SQLHANDLE * ) arg4));
			break;
		case 1:
			retval = (unsigned long) SQLParamOptions(((SQLHSTMT  ) arg2),((SQLUINTEGER  ) arg3),((SQLUINTEGER * ) arg4));
			break;
		case 2:
			retval = (unsigned long) SQLTransact(((SQLHENV  ) arg2),((SQLHDBC  ) arg3),((SQLUSMALLINT  ) arg4));
			break;
		case 3:
			retval = (unsigned long) SQLSetStmtOption(((SQLHSTMT  ) arg2),((SQLUSMALLINT  ) arg3),((SQLUINTEGER  ) arg4));
			break;
		case 4:
			retval = (unsigned long) SQLSetConnectOption(((SQLHDBC  ) arg2),((SQLUSMALLINT  ) arg3),((SQLUINTEGER  ) arg4));
			break;
		case 5:
			retval = (unsigned long) SQLPutData(((SQLHSTMT  ) arg2),((SQLPOINTER  ) arg3),((SQLINTEGER  ) arg4));
			break;
		case 6:
			retval = (unsigned long) SQLGetStmtOption(((SQLHSTMT  ) arg2),((SQLUSMALLINT  ) arg3),((SQLPOINTER  ) arg4));
			break;
		case 7:
			retval = (unsigned long) SQLGetFunctions(((SQLHDBC  ) arg2),((SQLUSMALLINT  ) arg3),((SQLUSMALLINT * ) arg4));
			break;
		case 8:
			retval = (unsigned long) SQLGetConnectOption(((SQLHDBC  ) arg2),((SQLUSMALLINT  ) arg3),((SQLPOINTER  ) arg4));
			break;
		case 9:
			retval = (unsigned long) SQLFetchScroll(((SQLHSTMT  ) arg2),((SQLSMALLINT  ) arg3),((SQLINTEGER  ) arg4));
			break;
		case 10:
			retval = (unsigned long) SQLEndTran(((SQLSMALLINT  ) arg2),((SQLHANDLE  ) arg3),((SQLSMALLINT  ) arg4));
			break;
		case 11:
			retval = (unsigned long) SQLAllocHandle(((SQLSMALLINT  ) arg2),((SQLHANDLE  ) arg3),((SQLHANDLE * ) arg4));
			break;
		default:
			PI_FAIL;
	}
	PI_makedouble(&rval,&rtype,(double) retval);
	if (PI_unify(arg5,type5,rval,rtype))
		PI_SUCCEED;
	PI_FAIL;
}
Exemple #12
0
HRESULT CNNTP::OnPost(IMessage * Msg, CdoEventStatus * EventStatus)
{
    HRESULT res;
    RETCODE rc;
    long global_read = 0;
    int to_inx = 0;
    SDWORD cbRet = SQL_DATA_AT_EXEC;
    if (EventStatus == NULL)
	return E_POINTER;

//    _Module.LogEvent ("Message");
    CComBSTR bStrTo, bStrBody, bStrFrom, bStrSubj, bStrCC, bStrBCC, bStrSentDate;
    CComPtr<_Stream> st;
    VARIANT sent_date;
    ::VariantInit (&sent_date);
    sent_date.vt = VT_DATE;

//    _Module.LogEvent ("After Subj");
    if (S_OK != (res = Msg->GetStream (&st)))
        return res;

//    _Module.LogEvent ("After Stream");

    CDBConnection *conn = _ppool->getConnection();
//    _Module.LogEvent ("After conn");
//    _Module.LogEvent ("From: %s, To: %s, CC: %s, BCC: %s, Subject: %s, SentOn :%s", 
//	szStrFrom, szStrTo, szStrCC, szStrBCC, szStrSubj, szStrSent);
    HSTMT hstmt = SQL_NULL_HSTMT;
    try 
    {
	int read, reconnect_count = 0;
	char szBuffer[4096];
again:
	hstmt = SQL_NULL_HSTMT;
	if (SQL_SUCCESS != SQLAllocStmt (conn->hdbc, &hstmt)) 
	    throw _T("SQLAllocStmt error");

//	SQLSetStmtOption (conn->hstmt, SQL_QUERY_TIMEOUT, 10);
	SQLSetParam (hstmt, 1, SQL_C_CHAR, SQL_LONGVARCHAR, 0, 0, (SQLPOINTER)2, &cbRet);
//        _Module.LogEvent ("After setparam");
	rc = SQLExecDirect (hstmt, (SQLCHAR *)"NS_POST (?)", SQL_NTS);
	if (rc != SQL_NEED_DATA && !reconnect_count)
	{
	    conn->ReportODBCError (hstmt, "Retry SQLExec error");
	    SQLFreeStmt (hstmt, SQL_DROP);
	    hstmt = SQL_NULL_HSTMT;
	    _Module.LogEvent ("Reconnecting ...");
	    reconnect_count = 1;
	    delete conn;
	    conn = new CDBConnection ();
	    goto again;
	}
	else if (rc != SQL_NEED_DATA)
	{
	    throw _T("SQLExec Error");
	}


  //      _Module.LogEvent ("After Exec");
	rc = SQLParamData (hstmt, NULL);
	if (rc != SQL_NEED_DATA)
	    throw _T("SQLParamData error");
//        _Module.LogEvent ("After ParamData");
	while (1) 
	{
	    st->ReadText (4096, &bStrBody);
	    read = wcslen (bStrBody);
	    global_read += read;
//	    _Module.LogEvent ("After ReadText");
	    if (!read)
		break;
	    ::WideCharToMultiByte (CP_ACP, 0, bStrBody, -1, szBuffer, sizeof (szBuffer), NULL, NULL);
	    rc = SQLPutData (hstmt, szBuffer, SQL_NTS);
//	    _Module.LogEvent ("After PutData");
	    if (rc != SQL_SUCCESS)
		throw _T("SQLPutData error");
	}
	rc = SQLParamData (hstmt, NULL);
//	_Module.LogEvent ("After ParamData");
	if (rc != SQL_SUCCESS)
	    throw _T("SQLParamData error");
	SQLFreeStmt (hstmt, SQL_DROP);
//	SQLFreeStmt (conn->hstmt, SQL_RESET_PARAMS);
	_Module.LogEvent ("NNTP Message (%ld chars) routed", global_read);
    }
    catch (TCHAR *ch)
    {
	conn->ReportODBCError (hstmt, ch);
	SQLFreeStmt (hstmt, SQL_DROP);
//	SQLFreeStmt (conn->hstmt, SQL_RESET_PARAMS);
	_ppool->releaseConnection(conn);
	return E_POINTER;
    }
    _ppool->releaseConnection(conn);
    return S_OK;
}
Exemple #13
0
int
main(int argc, char *argv[])
{
	SQLLEN ind;
	int len = strlen(test_text), n, i;
	const char *p;
	char *pp;
	SQLPOINTER ptr;
	unsigned char buf[256], *pb;
	SQLRETURN RetCode;
	int type, lc, sql_type;

	odbc_connect();

	/* create table to hold data */
	odbc_command("CREATE TABLE #putdata (c TEXT NULL, b IMAGE NULL)");

	sql_type = SQL_LONGVARCHAR;
	type = SQL_C_CHAR;
	lc = 1;
	for (;;) {
		CHKBindParameter(1, SQL_PARAM_INPUT, type, sql_type, 0, 0, (SQLPOINTER) 123, 0, &ind, "S");
		/* length required */
		ind = SQL_LEN_DATA_AT_EXEC(len * lc);

		/* 
		 * test for char 
		 */

		CHKPrepare((SQLCHAR *) "INSERT INTO #putdata(c) VALUES(?)", SQL_NTS, "S");

		CHKExecute("Ne");

		p = test_text;
		n = 5;
		CHKParamData(&ptr, "Ne");
		if (ptr != (SQLPOINTER) 123)
			ODBC_REPORT_ERROR("Wrong pointer from SQLParamData");
		while (*p) {
			int l = strlen(p);

			if (l < n)
				n = l;
			if (type == SQL_C_CHAR) {
				CHKPutData((char *) p, n, "S");
			} else {
				SQLWCHAR buf[256];
				CHKPutData((char *) buf, to_sqlwchar(buf, p, n), "S");
			}
			p += n;
			n *= 2;
		}
		CHKParamData(&ptr, "S");

		CHKParamData(&ptr, "E");

		/* check state  and reset some possible buffers */
		odbc_command("DECLARE @i INT");

		/* use server ntext if available */
		if (sql_type == SQL_LONGVARCHAR && odbc_db_is_microsoft() && odbc_db_version_int() >= 0x08000000u) {
			sql_type = SQL_WLONGVARCHAR;
			continue;
		}

		if (type != SQL_C_CHAR)
			break;
		sql_type = SQL_LONGVARCHAR;
		type = SQL_C_WCHAR;
		lc = sizeof(SQLWCHAR);
	}

	/* update row setting binary field */
	for (i = 0; i < 255; ++i)
		buf[i] = BYTE_AT(i);

	/* 
	 * test for binary 
	 */

	CHKBindParameter(1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, 0, 0, (SQLPOINTER) 4567, 0, &ind, "S");
	ind = SQL_LEN_DATA_AT_EXEC(254);

	CHKPrepare((SQLCHAR *) "UPDATE #putdata SET b = ?", SQL_NTS, "S");

	CHKExecute("Ne");

	pb = buf;
	n = 7;
	CHKParamData(&ptr, "Ne");
	if (ptr != (SQLPOINTER) 4567)
		ODBC_REPORT_ERROR("Wrong pointer from SQLParamData");
	while (pb != (buf + 254)) {
		int l = buf + 254 - pb;

		if (l < n)
			n = l;
		CHKPutData((char *) pb, n, "S");
		pb += n;
		n *= 2;
	}
	CHKParamData(&ptr, "S");

	CHKParamData(&ptr, "E");

	/* check state  and reset some possible buffers */
	odbc_command("DECLARE @i2 INT");


	CHKFreeStmt(SQL_RESET_PARAMS, "S");

	/* check inserts ... there should be all equal rows */
	strcpy(sql, "IF EXISTS(SELECT * FROM #putdata WHERE CONVERT(VARBINARY(255),b) <> 0x");
	/* append binary */
	for (i = 0; i < 254; ++i)
		sprintf(strchr(sql, 0), "%02x", buf[i]);
	strcat(sql, " OR CONVERT(VARCHAR(255),c) <> '");
	/* append string */
	pp = strchr(sql, 0);
	p = test_text;
	do {
		*pp++ = *p;
		if (*p == '\'')
			*pp++ = *p;
	} while(*p++);
	strcat(sql, "') SELECT 1");
	CheckNoRow(sql);

	odbc_command("DELETE FROM #putdata");

	/* test len == 0 case from ML */
	type = SQL_C_CHAR;
	for (;;) {
		CHKPrepare((SQLCHAR *) "INSERT INTO #putdata(c) VALUES(?)", SQL_NTS, "S");

		CHKBindParameter(1, SQL_PARAM_INPUT, type, SQL_LONGVARCHAR, 0, 0, (PTR) 2, 0, &ind, "S");

		ind = SQL_LEN_DATA_AT_EXEC(0);

		RetCode = CHKExecute("Ne");
		while (RetCode == SQL_NEED_DATA) {
			RetCode = SQLParamData(odbc_stmt, &ptr);
			if (RetCode == SQL_NEED_DATA) {
				if (type == SQL_C_CHAR) {
					SQLPutData(odbc_stmt, "abc", 3);
				} else {
					SQLWCHAR buf[10];
					SQLPutData(odbc_stmt, buf, to_sqlwchar(buf, "abc", 3));
				}
			}
		}
		if (type != SQL_C_CHAR)
			break;
		type = SQL_C_WCHAR;
		odbc_reset_statement();
	}

	/* check inserts ... */
	CheckNoRow("IF EXISTS(SELECT * FROM #putdata WHERE c NOT LIKE 'abc') SELECT 1");

	/* TODO test cancel inside SQLExecute */

	odbc_disconnect();

	printf("Done.\n");
	return 0;
}
Exemple #14
0
void
sql_blobInsert(const char *tabname, const char *colname, int rowid,
   const char *filename, void *offset, int length)
{
    char blobcmd[100];
    SQLINTEGER output_length;
    bool isfile;
    int fd;

    /* basic sanity checks */
    checkConnect();
    if(isnullstring(tabname))
	errorPrint("2blobInsert, null table name");
    if(isnullstring(colname))
	errorPrint("2blobInsert, null column name");
    if(rowid <= 0)
	errorPrint("2invalid rowid in blobInsert");
    if(length < 0)
	errorPrint("2invalid length in blobInsert");
    if(strlen(tabname) + strlen(colname) + 42 >= sizeof (blobcmd))
	errorPrint("@internal blobInsert command too long");

    isfile = true;
    if(isnullstring(filename)) {
	isfile = false;
	if(!offset)
	    errorPrint("2blobInsert is given null filename and null buffer");
    } else {
	offset = blobbuf;
	fd = eopen(filename, O_RDONLY | O_BINARY, 0);
	length = fileSizeByHandle(fd);
	if(length == 0) {
	    isfile = false;
	    close(fd);
	}
    }

    /* set up the blob insert command, using one host variable */
    sprintf(blobcmd, "update %s set %s = %s where rowid = %d",
       tabname, colname, (length ? "?" : "NULL"), rowid);
    stmt_text = blobcmd;
    debugStatement();
    newStatement();
    rv_lastNrows = 0;

    output_length = length;
    rc = SQL_SUCCESS;
    if(isfile) {
	output_length = SQL_LEN_DATA_AT_EXEC(length);
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
	   SQL_C_BINARY, SQL_LONGVARCHAR, length, 0,
	   blobcmd, length, &output_length);
	if(rc)
	    close(fd);
    } else if(length) {
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
	   SQL_C_BINARY, SQL_LONGVARCHAR, length, 0,
	   offset, length, &output_length);
    }
    if(errorTrap(0)) {
	SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
	return;
    }

    rc = SQLExecDirect(hstmt, blobcmd, SQL_NTS);
    SQLRowCount(hstmt, &rv_lastNrows);

    if(isfile) {
	if(rc != SQL_NEED_DATA) {
	    close(fd);
	    if(rc == SQL_SUCCESS)
		errorPrint("@blobInsert expected SQL_NEED_DATA");
	    errorTrap(0);
	    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
	    return;
	}

	output_length = 0;
	rc = SQLParamData(hstmt, (void **)&output_length);
	if((char *)output_length != blobcmd) {
	    close(fd);
	    errorPrint("2blobInsert got bad key from SQLParamData");
	}

	lseek(fd, 0L, 0);
	while(length) {
	    int n = length;
	    if(n > sizeof (blobbuf))
		n = sizeof (blobbuf);
	    if(read(fd, blobbuf, n) != n) {
		close(fd);
		errorPrint("2cannot read file %s, errno %d", filename, errno);
	    }
	    length -= n;

	    rc = SQLPutData(hstmt, blobbuf, n);
	    if(rc) {
		close(fd);
		errorTrap(0);
		SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
		return;
	    }
	}			/* loop reading the file */

	close(fd);

	/* since there are no more exec-time parameters,
	 * this call completes the execution of the SQL statement. */
	rc = SQLParamData(hstmt, (void **)&output_length);
    }

    if(errorTrap(0)) {
	SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
	return;
    }

    if(sql_debug)
	appendFile(sql_debuglog, "%d rows affected", rv_lastNrows);
    if(sql_debug2)
	printf("%d rows affected\n", rv_lastNrows);
    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
    exclist = 0;
}				/* sql_blobInsert */
int main(int argc, char **argv)
{
	SQLRETURN rc;
	HSTMT hstmt = SQL_NULL_HSTMT;
	char *param1, *param2;
	SQLLEN cbParam1, cbParam2;
	SQLLEN param1bytes, param2bytes;
	PTR paramid;
	SQLLEN str_ind_array[2];
	SQLUSMALLINT status_array[2];
	SQLULEN nprocessed = 0;
	int i;

	test_connect();

	rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	/****
	 * Bind with data-at-execution params. (VARBINARY)
	 */

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT id FROM byteatab WHERE t = ? OR t = ?", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	/* prepare the parameter values */
	param1 = "bar";
	param1bytes = strlen(param1);
	cbParam1 = SQL_DATA_AT_EXEC;
	param2 = "foobar";
	param2bytes = strlen(param2);
	cbParam2 = SQL_DATA_AT_EXEC;

	/* bind them. */
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_BINARY,	/* value type */
						  SQL_VARBINARY, /* param type */
						  param1bytes,	/* column size */
						  0,			/* dec digits */
						  (void *) 1,	/* param value ptr. For a data-at-exec
										 * param, this is a "parameter id" */
						  0,			/* buffer len */
						  &cbParam1		/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT,
						  SQL_C_BINARY,	/* value type */
						  SQL_VARBINARY, /* param type */
						  param2bytes,	/* column size */
						  0,			/* dec digits */
						  (void *) 2,	/* param value ptr. For a data-at-exec
										 * param, this is a "parameter id" */
						  0,			/* buffer len */
						  &cbParam2		/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	/* Execute */
	rc = SQLExecute(hstmt);
	if (rc != SQL_NEED_DATA)
		CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);

	/* set parameters */
	paramid = 0;
	while ((rc = SQLParamData(hstmt, &paramid)) == SQL_NEED_DATA)
	{
	  if (paramid == (void *) 1)
	  {
		  rc = SQLPutData(hstmt, param1, param1bytes);
		  CHECK_STMT_RESULT(rc, "SQLPutData failed", hstmt);
	  }
	  else if (paramid == (void *) 2)
	  {
		  rc = SQLPutData(hstmt, param2, param2bytes);
		  CHECK_STMT_RESULT(rc, "SQLPutData failed", hstmt);
	  }
	  else
	  {
		  printf("unexpected parameter id returned by SQLParamData: %p\n", paramid);
		  exit(1);
	  }
	}
	CHECK_STMT_RESULT(rc, "SQLParamData failed", hstmt);

	/* Fetch result */
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);


	/****
	 * Array binding with data-at-execution params.
	 */

	/* prepare the parameter values */
	str_ind_array[0] = SQL_DATA_AT_EXEC;
	str_ind_array[1] = SQL_DATA_AT_EXEC;

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT id FROM byteatab WHERE t = ?", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_BIND_TYPE, SQL_PARAM_BIND_BY_COLUMN, 0);
	SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_STATUS_PTR, status_array, 0);
	SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMS_PROCESSED_PTR, &nprocessed, 0);
	SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER) 2, 0);

	/* bind the array. */
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_BINARY,	/* value type */
						  SQL_VARBINARY, /* param type */
						  5,			/* column size */
						  0,			/* dec digits */
						  (void *) 1,	/* param value ptr. For a data-at-exec
										 * param, this is "parameter id" */
						  0,			/* buffer len */
						  str_ind_array	/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	/* Execute */
	rc = SQLExecute(hstmt);
	if (rc != SQL_NEED_DATA)
		CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);

	/* set parameters */
	paramid = 0;
	while ((rc = SQLParamData(hstmt, &paramid)) == SQL_NEED_DATA)
	{
		if (nprocessed == 1)
			rc = SQLPutData(hstmt, "foo", strlen("foo"));
		else if (nprocessed == 2)
			rc = SQLPutData(hstmt, "barf", strlen("barf"));
		else
		{
			printf("unexpected # of rows processed after SQL_NEED_DATA: %u\n", (unsigned int) nprocessed);
			exit(1);
		}
		CHECK_STMT_RESULT(rc, "SQLPutData failed", hstmt);
	}
	CHECK_STMT_RESULT(rc, "SQLParamData failed", hstmt);

	/* Fetch results */
	printf("Parameter	Status\n");
	for (i = 0; i < nprocessed; i++)
	{
		switch (status_array[i])
		{
			case SQL_PARAM_SUCCESS:
			case SQL_PARAM_SUCCESS_WITH_INFO:
				break;

			case SQL_PARAM_ERROR:
				printf("%d\tError\n", i);
				break;

			case SQL_PARAM_UNUSED:
				printf("%d\tUnused\n", i);
				break;

			case SQL_PARAM_DIAG_UNAVAILABLE:
				printf("%d\tDiag unavailable\n", i);
				break;
		}
	}

	printf ("Fetching result sets for array bound (%u results expected)\n",
			(unsigned int) nprocessed);
	for (i = 1; rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO; i++)
	{
		printf("%d: ", i);
		print_result(hstmt);

		rc = SQLMoreResults(hstmt);
	}
	if (rc != SQL_NO_DATA)
		CHECK_STMT_RESULT(rc, "SQLMoreResults failed", hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/* Clean up */
	test_disconnect();

	return 0;
}
int SSmain(int    argc, 
		SSchar* argv[])
{
	HDBC	hdbc;
	HENV	henv;
	HSTMT	hstmt;
	SQLRETURN  return_code;


	UTLDbUtlProgStart (argc, argv, SSText("log.txt"), DB_PD_DDL_EXPORT_PROCNAME);

	/*1. Connect to DB*/
	connectDB(&henv, &hdbc);

    /* HSTMT   hstmt_session;
    return_code = SQLAllocStmt ((SQLHDBC)hdbc, (SQLHSTMT *)&hstmt_session);
	if (return_code != SQL_SUCCESS)
	{
		printf("ERROR: The SQL statement did not execute successfully.\n");
		exit(1);
	}

   return_code = SQLExecDirect(hstmt_session, SSText("alter session set NLS_LANGUAGE='SIMPLIFIED CHINESE'"), -3);
   SQLFreeStmt(hstmt_session, SQL_DROP);*/

	/*3. Execute the SQL statement*/
	return_code = SQLAllocStmt ((SQLHDBC)hdbc, (SQLHSTMT *)&hstmt);
	if (return_code != SQL_SUCCESS)
	{  
		printf("ERROR: The SQL statement did not execute successfully.\n");
		exit(1);
	}
	
	SSchar*     pFilterStmt =  SSText("INSERT INTO TEST_CLOB_COL VALUES (?)");
	//SSchar*     pFilterStmt =  SSText("INSERT INTO test(LOG_DATA_1) VALUES (?)");
	return_code = SQLPrepare(hstmt, (SSuchar*)(pFilterStmt), SQL_NTS);   
	SSchar clobcol[] = {0x3042,0x3044,0x3046,0x3048,0x304A, 0x0000};
   /* test 1:
	LONG        cbRowId = 10;
	//return_code= SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_VARCHAR, 4000, 0, clobcol, sizeof(clobcol), &cbRowId); //This is ok!
	return_code= SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_LONGVARCHAR, 40, 0, clobcol, 10, &cbRowId);
    
	return_code = SQLExecute((SQLHSTMT)hstmt); 
   */

   /*test 2*/
   //test a: LONG cbRowId = SQL_DATA_AT_EXEC;
   LONG cbRowId = SQL_LEN_DATA_AT_EXEC(11);
   return_code= SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_LONGVARCHAR, 40, 0, clobcol, 10, &cbRowId);
   return_code = SQLExecute((SQLHSTMT)hstmt);
   SSchar *buf = clobcol;
   return_code = SQLParamData(hstmt, (SQLPOINTER *)&buf);
   return_code = SQLPutData(hstmt, buf, 10);
   return_code = SQLParamData(hstmt, (SQLPOINTER *)&buf);

	if (return_code == SQL_SUCCESS)
	{
		printf("The SQL statement executed successfully.\n");
	}
	else{
		printf("The SQL statement did not execute successfully.\n");
		ODBC_error ((HENV)henv, (HDBC)hdbc, (HSTMT)hstmt) ;
	}

   SSchar*     pSelectStmt =  SSText("select userenv('language') from dual");
	//SSchar*     pFilterStmt =  SSText("INSERT INTO test(LOG_DATA_1) VALUES (?)");
	return_code = SQLPrepare(hstmt, (SSuchar*)(pSelectStmt), SQL_NTS);

	return_code = SQLExecute((SQLHSTMT)hstmt); 
   

	SQLDisconnect ((SQLHDBC)hdbc);
	SQLFreeConnect ((SQLHDBC)hdbc);
	SQLFreeEnv ((SQLHENV)henv);

	return(return_code);
}
Exemple #17
0
SQLRETURN SendLongData(void)
{
	// Declare The Local Memory Variables

	SQLPOINTER Value;
	SQLCHAR Buffer[20];
	SQLCHAR InputParam[] = "Special Instructions";
	size_t DataSize = 0;
	unsigned char in_data[200];
	int i;
	for (i = 0; i < BUFSIZE; i++)
		in_data[i] = (unsigned char)(BUFSIZE - 1 - i);
	// Start The Data-At-Execution Sequence By Calling 
	// SQLParamData()
	rc = SQLParamData(StmtHandle, (SQLPOINTER *) & Value);
	VERBOSE("returned a value of  %s\n", (const char *)Value);
	// Examine The Contents Of Value (Returned By SQLParamData())
	// To Determine Which Data-At-Execution Parameter Currently
	// Needs Data
	if (strcmp((const char *)Value, (const char *)InputParam) == 0
	    && rc == SQL_NEED_DATA) {
		// As Long As Data Is Available For The Parameter, Retrieve
		// Part Of It From The External Data File And Send It To The
		// Data Source
		// while (InFile.get(Buffer, sizeof(Buffer)))
		//{
		while (DataSize < BUFSIZE) {
			for (i = DataSize; i < DataSize + CHUNKSIZE; i++) {
				Buffer[i - DataSize] = in_data[i];
				VERBOSE("Buffer[%d]=in_data[%d]=%d\n",
					i - DataSize, i, in_data[i]);
			}

			rc = SQLPutData(StmtHandle, (SQLPOINTER) Buffer,
					CHUNKSIZE);
			assert(rc == SQL_SUCCESS
			       || rc == SQL_SUCCESS_WITH_INFO);
			DataSize = DataSize + CHUNKSIZE;

			// If The Amount Of Data Retrieved Exceeds The Size Of 
			// The Column (Which Is 200 Bytes), Call The SQLCancel() 
			// Function To Terminate The Data-At-Execution 
			// Sequence And Exit
			if (DataSize > BUFSIZE) {
				rc = SQLCancel(StmtHandle);
				return (SQL_ERROR);
			}
		}

		// Call SQLParamData() Again To Terminate The 
		// Data-At-Execution Sequence
		rc = SQLParamData(StmtHandle, (SQLPOINTER *) & Value);

		// Display A Message Telling How Many Bytes Of Data Were Sent
		if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
			VERBOSE("Successfully inserted %d\n", DataSize);
			VERBOSE(" bytes of data into the database.\n");
		}

	}
	// Close The External Data File
	//InFile.close();

	// Return The ODBC API Return Code To The Calling Function 
	return (rc);
}