Ejemplo n.º 1
0
/* call-seq: client.prepare # => Mysql2::Statement
 *
 * Create a new prepared statement.
 */
static VALUE prepare_statement(VALUE self, VALUE sql) {
  GET_CLIENT(self);
  struct nogvl_prepare_statement_args args;
  MYSQL_STMT *stmt;
  VALUE rb_stmt;
  my_bool truth = 1;

  stmt = mysql_stmt_init(wrapper->client);
  if (stmt == NULL) {
    rb_raise(cMysql2Error, "Unable to initialize prepared statement: out of memory");
  }

  if (mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &truth)) {
    rb_raise(cMysql2Error, "Unable to initialize prepared statement");
  }

  rb_stmt = Data_Wrap_Struct(cMysql2Statement, 0, mysql_stmt_close, stmt);

  args.stmt = stmt;
  args.sql = StringValuePtr(sql);
  args.sql_len = RSTRING_LEN(sql);

  if (rb_thread_blocking_region(nogvl_prepare_statement, &args, RUBY_UBF_IO, 0) == Qfalse) {
    rb_raise(cMysql2Error, "%s", mysql_stmt_error(stmt));
  }

  return rb_stmt;
}
Ejemplo n.º 2
0
bool MySQLPreparedStatement::execute()
{
    doQuery();
    my_bool    bool_tmp=1;
    mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bool_tmp);
    //mysql_stmt_store_result(stmt);
    return (mysql_stmt_field_count(stmt) > 0);
}
Ejemplo n.º 3
0
VALUE rb_mysql_stmt_new(VALUE rb_client, VALUE sql) {
  mysql_stmt_wrapper *stmt_wrapper;
  VALUE rb_stmt;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *conn_enc;
#endif

  Check_Type(sql, T_STRING);

  rb_stmt = Data_Make_Struct(cMysql2Statement, mysql_stmt_wrapper, rb_mysql_stmt_mark, rb_mysql_stmt_free, stmt_wrapper);
  {
    stmt_wrapper->client = rb_client;
    stmt_wrapper->refcount = 1;
    stmt_wrapper->closed = 0;
    stmt_wrapper->stmt = NULL;
  }

  // instantiate stmt
  {
    GET_CLIENT(rb_client);
    stmt_wrapper->stmt = mysql_stmt_init(wrapper->client);
#ifdef HAVE_RUBY_ENCODING_H
    conn_enc = rb_to_encoding(wrapper->encoding);
#endif
  }
  if (stmt_wrapper->stmt == NULL) {
    rb_raise(cMysql2Error, "Unable to initialize prepared statement: out of memory");
  }

  // set STMT_ATTR_UPDATE_MAX_LENGTH attr
  {
    my_bool truth = 1;
    if (mysql_stmt_attr_set(stmt_wrapper->stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &truth)) {
      rb_raise(cMysql2Error, "Unable to initialize prepared statement: set STMT_ATTR_UPDATE_MAX_LENGTH");
    }
  }

  // call mysql_stmt_prepare w/o gvl
  {
    struct nogvl_prepare_statement_args args;
    args.stmt = stmt_wrapper->stmt;
    args.sql = sql;
#ifdef HAVE_RUBY_ENCODING_H
    // ensure the string is in the encoding the connection is expecting
    args.sql = rb_str_export_to_enc(args.sql, conn_enc);
#endif
    args.sql_ptr = RSTRING_PTR(sql);
    args.sql_len = RSTRING_LEN(sql);

    if ((VALUE)rb_thread_call_without_gvl(nogvl_prepare_statement, &args, RUBY_UBF_IO, 0) == Qfalse) {
      rb_raise_mysql2_stmt_error(stmt_wrapper);
    }
  }

  return rb_stmt;
}
Ejemplo n.º 4
0
MySQLPreparedStatement::MySQLPreparedStatement(MYSQL_STMT* stmt) :
        m_Mstmt(stmt), m_bind(NULL) {
    /// Initialize variable parameters
    m_paramCount = mysql_stmt_param_count(stmt);
    m_paramsSet.assign(m_paramCount, false);
    m_bind = new MYSQL_BIND[m_paramCount];
    memset(m_bind, 0, sizeof(MYSQL_BIND) * m_paramCount);

    /// "If set to 1, causes mysql_stmt_store_result() to update the metadata MYSQL_FIELD->max_length value."
    my_bool bool_tmp = 1;
    mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bool_tmp);
}
Ejemplo n.º 5
0
MySQLPreparedStatement::MySQLPreparedStatement(MySQLConnection* conn, MYSQL_STMT* stmt) :
        mysqlConn(conn),
        closed(false),
        stmt(stmt),
        bind(NULL)
{
    paramCount = mysql_stmt_param_count(stmt);
    paramsSet.assign(paramCount, false);
    bind = new MYSQL_BIND[paramCount];
    ACE_OS::memset(bind, 0, sizeof(MYSQL_BIND) * paramCount);
    my_bool    bool_tmp=1;
    mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bool_tmp);
}
Ejemplo n.º 6
0
ResultSet_T MysqlPreparedStatement_executeQuery(T P) {
        assert(P);
        if (P->parameterCount > 0)
                if ((P->lastError = mysql_stmt_bind_param(P->stmt, P->bind)))
                        THROW(SQLException, "%s", mysql_stmt_error(P->stmt));
#if MYSQL_VERSION_ID >= 50002
        unsigned long cursor = CURSOR_TYPE_READ_ONLY;
        mysql_stmt_attr_set(P->stmt, STMT_ATTR_CURSOR_TYPE, &cursor);
#endif
        if ((P->lastError = mysql_stmt_execute(P->stmt)))
                THROW(SQLException, "%s", mysql_stmt_error(P->stmt));
        if (P->lastError == MYSQL_OK)
                return ResultSet_new(MysqlResultSet_new(P->stmt, P->maxRows, true), (Rop_T)&mysqlrops);
        THROW(SQLException, "%s", mysql_stmt_error(P->stmt));
        return NULL;
}
Ejemplo n.º 7
0
void MysqlPreparedStatement_execute(T P) {
        assert(P);
        if (P->parameterCount > 0)
                if ((P->lastError = mysql_stmt_bind_param(P->stmt, P->bind)))
                        THROW(SQLException, "%s", mysql_stmt_error(P->stmt));
#if MYSQL_VERSION_ID >= 50002
        unsigned long cursor = CURSOR_TYPE_NO_CURSOR;
        mysql_stmt_attr_set(P->stmt, STMT_ATTR_CURSOR_TYPE, &cursor);
#endif
        if ((P->lastError = mysql_stmt_execute(P->stmt)))
                THROW(SQLException, "%s", mysql_stmt_error(P->stmt));
        if (P->lastError == MYSQL_OK) {
                /* Discard prepared param data in client/server */
                P->lastError = mysql_stmt_reset(P->stmt);
        }
}
Ejemplo n.º 8
0
MYSQL_STMT* MADB_NewStmtHandle(MADB_Stmt *Stmt)
{
  static const my_bool UpdateMaxLength= 1;
  MYSQL_STMT* stmt= mysql_stmt_init(Stmt->Connection->mariadb);

  if (stmt != NULL)
  {
    mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &UpdateMaxLength);
  }
  else
  {
    MADB_SetError(&Stmt->Error, MADB_ERR_HY001, NULL, 0);
  }

  return stmt;
}
Ejemplo n.º 9
0
MError MMysqlCommand::DoExecuteReader()
{
    int param_count = mysql_stmt_param_count(p_stmt_);
    if (static_cast<size_t>(param_count) != in_params_.size())
    {
        MLOG(MGetLibLogger(), MERR, "param count is not match need:", param_count, " actual is :", in_params_.size());
        return MError::NotMatch;
    }
    if (mysql_stmt_bind_param(p_stmt_, &in_params_[0]) != 0)
    {
        MLOG(MGetLibLogger(), MERR, "bind failed errno:", mysql_stmt_errno(p_stmt_), " error:", mysql_stmt_error(p_stmt_));
        return MError::Unknown;
    }
    my_bool update_max_length = 1;
    mysql_stmt_attr_set(p_stmt_, STMT_ATTR_UPDATE_MAX_LENGTH, static_cast<void*>(&update_max_length));
    if (mysql_stmt_execute(p_stmt_) != 0)
    {
        MLOG(MGetLibLogger(), MERR, "execute failed errno:", mysql_stmt_errno(p_stmt_), " error:", mysql_stmt_error(p_stmt_));
        return MError::Unknown;
    }
    return BindResult();
}
Ejemplo n.º 10
0
ResultSet_T MysqlConnection_executeQuery(T C, const char *sql, va_list ap) {
        va_list ap_copy;
        MYSQL_STMT *stmt = NULL;
	assert(C);
        StringBuffer_clear(C->sb);
        va_copy(ap_copy, ap);
        StringBuffer_vappend(C->sb, sql, ap_copy);
        va_end(ap_copy);
        if (prepare(C, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), &stmt)) {
#if MYSQL_VERSION_ID >= 50002
                unsigned long cursor = CURSOR_TYPE_READ_ONLY;
                mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, &cursor);
#endif
                if ((C->lastError = mysql_stmt_execute(stmt))) {
                        StringBuffer_clear(C->sb);
                        StringBuffer_append(C->sb, "%s", mysql_stmt_error(stmt));
                        mysql_stmt_close(stmt);
                }
                else
                        return ResultSet_new(MysqlResultSet_new(stmt, C->maxRows, false), (Rop_T)&mysqlrops);
        }
        return NULL;
}
Ejemplo n.º 11
0
void
gda_mysql_recordset_set_chunk_size (GdaMysqlRecordset  *recset,
				    gint                chunk_size)
{
	g_return_if_fail (GDA_IS_MYSQL_RECORDSET (recset));

	if (recset->priv->mysql_stmt == NULL)  // Creation is in progress so it's not set.
		return;

#if MYSQL_VERSION_ID >= 50002
	const unsigned long prefetch_rows = chunk_size;
	if (mysql_stmt_attr_set (recset->priv->mysql_stmt, STMT_ATTR_PREFETCH_ROWS,
				 (void *) &prefetch_rows)) {
		g_warning ("%s: %s\n", __func__, mysql_stmt_error (recset->priv->mysql_stmt));
		return;
	}
	recset->priv->chunk_size = chunk_size;
	g_object_notify (G_OBJECT(recset), "chunk-size");
#else
	g_warning (_("Could not use CURSOR. Mysql version 5.0 at least is required. "
		     "Chunk size ignored."));
#endif
}
Ejemplo n.º 12
0
static GtRDBStmt* gt_rdb_mysql_prepare(GtRDB *rdb, const char *query,
                                       GtUword num_params, GtError *err)
{
  GtRDBStmt *st = NULL;
  GtRDBStmtMySQL *stm = NULL;
  GtRDBMySQL *rdbm;
  int had_err = 0, retval = 0;
  /* we need these to keep track of result/parameter and string buffers */
  HashElemInfo str_buffer_hash = {
      gt_ht_ptr_elem_hash,
      { free_str },
      sizeof (GtStr*),
      gt_ht_ptr_elem_cmp,
      NULL,
      NULL
    },
    buffer_hash = {
      gt_ht_ptr_elem_hash,
      { free_buf },
      sizeof (void*),
      gt_ht_ptr_elem_cmp,
      NULL,
      NULL
    };
  MYSQL_STMT *tmp = NULL;
  gt_assert(rdb && query);
  gt_error_check(err);

  rdbm = gt_rdb_mysql_cast(rdb);
  tmp = mysql_stmt_init(&rdbm->conn);
  if ((retval = mysql_stmt_prepare(tmp, query, strlen(query)))) {
    gt_error_set(err, GT_MYSQL_ERRMSG, retval, mysql_stmt_error(tmp));
    had_err = -1;
  }
  if (!had_err) {
    int param_count;
    param_count = mysql_stmt_param_count(tmp);
    if (param_count != num_params) {
      gt_error_set(err, "invalid parameter count: "GT_WU" expected, %d given",
                   num_params, param_count);
      mysql_stmt_close(tmp);
      had_err = -1;
    }
  }
  if (!had_err) {
    st = gt_rdb_stmt_create(gt_rdb_stmt_mysql_class());
    stm = gt_rdb_stmt_mysql_cast(st);
    stm->num_params = num_params;
    stm->query = gt_str_new_cstr(query);
    stm->buffers = gt_hashtable_new(buffer_hash);
    stm->returned_strings = gt_hashtable_new(str_buffer_hash);
    stm->stmt = tmp;
    stm->update_maxlengths = true;
    stm->params = gt_calloc(num_params, sizeof (MYSQL_BIND));
    mysql_stmt_attr_set(tmp, STMT_ATTR_UPDATE_MAX_LENGTH,
                        &stm->update_maxlengths);
    memset(stm->params, 0, num_params*sizeof (MYSQL_BIND));
    stm->conn = &rdbm->conn;
  }
  return st;
}
Ejemplo n.º 13
0
static int my_process_stmt_result(MYSQL_STMT *stmt)
{
 int         field_count;
 int         row_count= 0;
 MYSQL_BIND  buffer[MAX_RES_FIELDS];
 MYSQL_FIELD *field;
 MYSQL_RES   *result;
 char        data[MAX_RES_FIELDS][MAX_FIELD_DATA_SIZE];
 ulong       length[MAX_RES_FIELDS];
 my_bool     is_null[MAX_RES_FIELDS];
 int         rc, i;

 if (!(result= mysql_stmt_result_metadata(stmt))) /* No meta info */
 {
   while (!mysql_stmt_fetch(stmt))
   row_count++;
   return row_count;
 }

 field_count= MY_MIN(mysql_num_fields(result), MAX_RES_FIELDS);

 memset(buffer, 0, sizeof(buffer));
 memset(length, 0, sizeof(length));
 memset(is_null, 0, sizeof(is_null));

 for(i= 0; i < field_count; i++)
 {
   buffer[i].buffer_type= MYSQL_TYPE_STRING;
   buffer[i].buffer_length= MAX_FIELD_DATA_SIZE;
   buffer[i].length= &length[i];
   buffer[i].buffer= (void *) data[i];
   buffer[i].is_null= &is_null[i];
 }

 rc= mysql_stmt_bind_result(stmt, buffer);
 check_execute(stmt, rc);

 rc= 1;
 mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, (void*)&rc);
 rc= mysql_stmt_store_result(stmt);
 check_execute(stmt, rc);
 my_print_result_metadata(result);

 mysql_field_seek(result, 0);
 while ((rc= mysql_stmt_fetch(stmt)) == 0)
 {
   if (!opt_silent)
   {
     fputc('\t', stdout);
     fputc('|', stdout);
   }
   mysql_field_seek(result, 0);
   for (i= 0; i < field_count; i++)
   {
     field= mysql_fetch_field(result);
     if (!opt_silent)
     {
       if (is_null[i])
       fprintf(stdout, " %-*s |", (int) field->max_length, "NULL");
       else if (length[i] == 0)
       {
	 data[i][0]= '\0';  /* unmodified buffer */
	 fprintf(stdout, " %*s |", (int) field->max_length, data[i]);
       }
       else if (IS_NUM(field->type))
       fprintf(stdout, " %*s |", (int) field->max_length, data[i]);
       else
       fprintf(stdout, " %-*s |", (int) field->max_length, data[i]);
     }
   }
   if (!opt_silent)
   {
     fputc('\t', stdout);
     fputc('\n', stdout);
   }
   row_count++;
 }
 DIE_UNLESS(rc == MYSQL_NO_DATA);
 if (!opt_silent)
 {
   if (row_count)
   my_print_dashes(result);
   fprintf(stdout, "\n\t%d %s returned\n", row_count,
   row_count == 1 ? "row" : "rows");
 }
 mysql_free_result(result);
 return row_count;
}
Ejemplo n.º 14
0
void stmt_fetch_init(Stmt_fetch *fetch, unsigned stmt_no_arg,
const char *query_arg)
{
 unsigned long type= CURSOR_TYPE_READ_ONLY;
 int rc;
 unsigned i;
 MYSQL_RES *metadata;
 DBUG_ENTER("stmt_fetch_init");

 /* Save query and statement number for error messages */
 fetch->stmt_no= stmt_no_arg;
 fetch->query= query_arg;

 fetch->handle= mysql_stmt_init(mysql);

 rc= mysql_stmt_prepare(fetch->handle, fetch->query, (ulong)strlen(fetch->query));
 check_execute(fetch->handle, rc);

 /*
 The attribute is sent to server on execute and asks to open read-only
 for result set
 */
 mysql_stmt_attr_set(fetch->handle, STMT_ATTR_CURSOR_TYPE,
 (const void*) &type);

 rc= mysql_stmt_execute(fetch->handle);
 check_execute(fetch->handle, rc);

 /* Find out total number of columns in result set */
 metadata= mysql_stmt_result_metadata(fetch->handle);
 fetch->column_count= mysql_num_fields(metadata);
 mysql_free_result(metadata);

 /*
 Now allocate bind handles and buffers for output data:
 calloc memory to reduce number of MYSQL_BIND members we need to
 set up.
 */

 fetch->bind_array= (MYSQL_BIND *) calloc(1, sizeof(MYSQL_BIND) *
 fetch->column_count);
 fetch->out_data= (char**) calloc(1, sizeof(char*) * fetch->column_count);
 fetch->out_data_length= (ulong*) calloc(1, sizeof(ulong) *
                                         fetch->column_count);
 for (i= 0; i < fetch->column_count; ++i)
 {
   fetch->out_data[i]= (char*) calloc(1, MAX_COLUMN_LENGTH);
   fetch->bind_array[i].buffer_type= MYSQL_TYPE_STRING;
   fetch->bind_array[i].buffer= fetch->out_data[i];
   fetch->bind_array[i].buffer_length= MAX_COLUMN_LENGTH;
   fetch->bind_array[i].length= fetch->out_data_length + i;
 }

 mysql_stmt_bind_result(fetch->handle, fetch->bind_array);

 fetch->row_count= 0;
 fetch->is_open= TRUE;

 /* Ready for reading rows */
 DBUG_VOID_RETURN;
}
Ejemplo n.º 15
0
bool
DbUtil::runQuery(const char* sql,
                 const Properties& args,
                 SqlResultSet& rows){

  clear_error();
  rows.clear();
  if (!isConnected())
    return false;
  assert(m_mysql);

  g_debug << "runQuery: " << endl
          << " sql: '" << sql << "'" << endl;


  MYSQL_STMT *stmt= mysql_stmt_init(m_mysql);
  if (mysql_stmt_prepare(stmt, sql, (unsigned long)strlen(sql)))
  {
    report_error("Failed to prepare: ", m_mysql);
    return false;
  }

  uint params= mysql_stmt_param_count(stmt);
  MYSQL_BIND *bind_param = new MYSQL_BIND[params];
  NdbAutoObjArrayPtr<MYSQL_BIND> _guard(bind_param);

  memset(bind_param, 0, params * sizeof(MYSQL_BIND));

  for(uint i= 0; i < mysql_stmt_param_count(stmt); i++)
  {
    BaseString name;
    name.assfmt("%d", i);
    // Parameters are named 0, 1, 2...
    if (!args.contains(name.c_str()))
    {
      g_err << "param " << i << " missing" << endl;
      assert(false);
    }
    PropertiesType t;
    Uint32 val_i;
    const char* val_s;
    args.getTypeOf(name.c_str(), &t);
    switch(t) {
    case PropertiesType_Uint32:
      args.get(name.c_str(), &val_i);
      bind_param[i].buffer_type= MYSQL_TYPE_LONG;
      bind_param[i].buffer= (char*)&val_i;
      g_debug << " param" << name.c_str() << ": " << val_i << endl;
      break;
    case PropertiesType_char:
      args.get(name.c_str(), &val_s);
      bind_param[i].buffer_type= MYSQL_TYPE_STRING;
      bind_param[i].buffer= (char*)val_s;
      bind_param[i].buffer_length= (unsigned long)strlen(val_s);
      g_debug << " param" << name.c_str() << ": " << val_s << endl;
      break;
    default:
      assert(false);
      break;
    }
  }
  if (mysql_stmt_bind_param(stmt, bind_param))
  {
    report_error("Failed to bind param: ", m_mysql);
    mysql_stmt_close(stmt);
    return false;
  }

  if (mysql_stmt_execute(stmt))
  {
    report_error("Failed to execute: ", m_mysql);
    mysql_stmt_close(stmt);
    return false;
  }

  /*
    Update max_length, making it possible to know how big
    buffers to allocate
  */
  my_bool one= 1;
  mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, (void*) &one);

  if (mysql_stmt_store_result(stmt))
  {
    report_error("Failed to store result: ", m_mysql);
    mysql_stmt_close(stmt);
    return false;
  }

  uint row= 0;
  MYSQL_RES* res= mysql_stmt_result_metadata(stmt);
  if (res != NULL)
  {
    MYSQL_FIELD *fields= mysql_fetch_fields(res);
    uint num_fields= mysql_num_fields(res);
    MYSQL_BIND *bind_result = new MYSQL_BIND[num_fields];
    NdbAutoObjArrayPtr<MYSQL_BIND> _guard1(bind_result);
    memset(bind_result, 0, num_fields * sizeof(MYSQL_BIND));

    for (uint i= 0; i < num_fields; i++)
    {
      unsigned long buf_len= sizeof(int);

      switch(fields[i].type){
      case MYSQL_TYPE_STRING:
        buf_len = fields[i].length + 1;
        break;
      case MYSQL_TYPE_VARCHAR:
      case MYSQL_TYPE_VAR_STRING:
        buf_len= fields[i].max_length + 1;
        break;
      case MYSQL_TYPE_LONGLONG:
        buf_len= sizeof(long long);
        break;
      case MYSQL_TYPE_LONG:
        buf_len = sizeof(long);
        break;
      default:
        break;
      }
      
      bind_result[i].buffer_type= fields[i].type;
      bind_result[i].buffer= malloc(buf_len);
      bind_result[i].buffer_length= buf_len;
      bind_result[i].is_null = (my_bool*)malloc(sizeof(my_bool));
      * bind_result[i].is_null = 0;
    }

    if (mysql_stmt_bind_result(stmt, bind_result)){
      report_error("Failed to bind result: ", m_mysql);
      mysql_stmt_close(stmt);
      return false;
    }

    while (mysql_stmt_fetch(stmt) != MYSQL_NO_DATA)
    {
      Properties curr(true);
      for (uint i= 0; i < num_fields; i++){
        if (* bind_result[i].is_null)
          continue;
        switch(fields[i].type){
        case MYSQL_TYPE_STRING:
	  ((char*)bind_result[i].buffer)[fields[i].max_length] = 0;
        case MYSQL_TYPE_VARCHAR:
        case MYSQL_TYPE_VAR_STRING:
          curr.put(fields[i].name, (char*)bind_result[i].buffer);
          break;

        case MYSQL_TYPE_LONGLONG:
          curr.put64(fields[i].name,
                     *(unsigned long long*)bind_result[i].buffer);
          break;

        default:
          curr.put(fields[i].name, *(int*)bind_result[i].buffer);
          break;
        }
      }
      rows.put("row", row++, &curr);
    }

    mysql_free_result(res);

    for (uint i= 0; i < num_fields; i++)
    {
      free(bind_result[i].buffer);
      free(bind_result[i].is_null);
    }
  }

  // Save stats in result set
  rows.put("rows", row);
  rows.put64("affected_rows", mysql_affected_rows(m_mysql));
  rows.put("mysql_errno", mysql_errno(m_mysql));
  rows.put("mysql_error", mysql_error(m_mysql));
  rows.put("mysql_sqlstate", mysql_sqlstate(m_mysql));
  rows.put64("insert_id", mysql_insert_id(m_mysql));

  mysql_stmt_close(stmt);
  return true;
}
Ejemplo n.º 16
0
int sqlrow(DB db,SQL sql,const char *format,...)
{
	int i;
	my_bool w;
	int *ii;
	char **t;
	MYSQL_FIELD *f;
	va_list ap;

	if(!db||!sql)
	{
		printf("sqlrow: bad database/query handle\n");
		return -1;
	}

	if(!sql->result)
	{
		w=1;
		if(mysql_stmt_attr_set(sql->sql,STMT_ATTR_UPDATE_MAX_LENGTH,&w))
		{
			printf("sqlsetattr: %s\n",mysql_stmt_error(sql->sql));
			goto out0;
		}
		if(mysql_stmt_execute(sql->sql))
		{
			printf("sqlexecute: %s\n",mysql_stmt_error(sql->sql));
			goto out0;
		}
		if(!(sql->restotal=mysql_stmt_field_count(sql->sql)))return 1;
		if(mysql_stmt_store_result(sql->sql))
		{
			printf("sqlstore: %s\n",mysql_stmt_error(sql->sql));
			goto out0;
		}
		if(!(sql->result=mysql_stmt_result_metadata(sql->sql)))return 1;
		if(!(f=mysql_fetch_fields(sql->result)))
		{
			printf("sqlfields: %s\n",mysql_stmt_error(sql->sql));
			goto out0;
		}
		if(!(sql->reslbuf=malloc(sql->restotal*sizeof(unsigned long))))
		{
			printf("sqlrow: out of memory\n");
			goto out0;
		}
		if(!(sql->resibuf=malloc(sql->restotal*sizeof(int))))
		{
			printf("sqlrow: out of memory\n");
			goto out0;
		}
		if(!(sql->resparam=malloc(sql->restotal*sizeof(MYSQL_BIND))))
		{
			printf("sqlrow: out of memory\n");
			goto out0;
		}
		memset(sql->resparam,0,sql->restotal*sizeof(MYSQL_BIND));
		for(i=0;i<sql->restotal;i++)switch(f[i].type)
		{
		case FIELD_TYPE_TINY:
		case FIELD_TYPE_SHORT:
		case FIELD_TYPE_LONG:
		case FIELD_TYPE_LONGLONG:
		case FIELD_TYPE_INT24:
			sql->resparam[i].buffer_type=MYSQL_TYPE_LONG;
			sql->resparam[i].buffer=&sql->resibuf[i];
			break;

		case FIELD_TYPE_STRING:
		case FIELD_TYPE_VAR_STRING:
		case FIELD_TYPE_BLOB:
			sql->resparam[i].buffer_type=MYSQL_TYPE_BLOB;
			sql->resparam[i].buffer_length=f[i].max_length+1;
			sql->resparam[i].length=&sql->reslbuf[i];
			if(!(sql->resparam[i].buffer=malloc(f[i].max_length+1)))
			{
				while(i--)if(sql->resparam[i].buffer_type==
					MYSQL_TYPE_BLOB)
					free(sql->resparam[i].buffer);
				free(sql->resparam);
				sql->resparam=NULL;
				printf("sqlrow: out of memory\n");
				goto out0;
			}
			break;

		default:
			printf("sqlrow: unknown field type %d\n",f[i].type);
			return -1;
		}
		if(mysql_stmt_bind_result(sql->sql,sql->resparam))
		{
			printf("sqlresbind: %s\n",mysql_stmt_error(sql->sql));
			goto out0;
		}
	}

	if(mysql_stmt_fetch(sql->sql))return 1;

	va_start(ap,format);
	for(i=0;*format;i++)if(i==sql->restotal)
	{
		va_end(ap);
		goto out1;
	}
	else switch(*format++)
	{
	case 'i':
		if(sql->resparam[i].buffer_type!=MYSQL_TYPE_LONG)
		{
			va_end(ap);
			goto out1;
		}
		ii=va_arg(ap,int *);
		*ii=sql->resibuf[i];
		break;
		break;
	case 't':
		if(sql->resparam[i].buffer_type!=MYSQL_TYPE_BLOB)
		{
			va_end(ap);
			goto out1;
		}
		t=va_arg(ap,char **);
		*t=sql->resparam[i].buffer;
		(*t)[sql->reslbuf[i]]=0;
		break;
	default:printf("unknown format %c\n",format[-1]);
		va_end(ap);
		goto out0;
	}
	va_end(ap);

	return 0;

out1:	printf("sqlrow format mismatch\n");
out0:	return -1;
}
Ejemplo n.º 17
0
void Statement::Prepare() {
	if (! _db.IsConnected()) {
		throw DatabaseException("Error in Statement::Prepare", 0, "----", "Database is not connected");
	}

	_numberAffectedRows = 0;

	if ((_stmt = mysql_stmt_init(_db._db)) == NULL) {
		throw DatabaseException(_db._db, "Error in Statement::Prepare during initialize");
	}

	if (mysql_stmt_prepare(_stmt, _sqlStatement.c_str(), _sqlStatement.length()) != 0) {
		mysql_stmt_close(_stmt);
		throw DatabaseException(_stmt, "Error in Statement::Prepare during prepare");
	}

	_bind = NULL;
	unsigned long parameterCount = ParameterCount();
	if (parameterCount > 0) {
		_bind = (MYSQL_BIND *) malloc(sizeof(MYSQL_BIND) * parameterCount);
		memset(_bind, 0, sizeof(MYSQL_BIND) * parameterCount);
	}

	_numberResultColumns = 0;
	_hasBlobField = false;

	MYSQL_RES *metaData;
	if ((metaData = mysql_stmt_result_metadata(_stmt)) == NULL) {
		return;
	}

	_resultBind = NULL;
	_numberResultColumns = mysql_num_fields(metaData);
	if (_numberResultColumns > 0) {
		_resultBind = (MYSQL_BIND *) malloc(sizeof(MYSQL_BIND) * _numberResultColumns);
		memset(_resultBind, 0, sizeof(MYSQL_BIND) * _numberResultColumns);
	}

	int fieldPos = 0;
	MYSQL_FIELD *field;
	while ((field = mysql_fetch_field(metaData)) != NULL) {
		ParamBuffer *buffer = NULL;

		if ((field->type == MYSQL_TYPE_VAR_STRING) || 
		    (field->type == MYSQL_TYPE_STRING) ||
		    (field->type == MYSQL_TYPE_DECIMAL) ||
		    (field->type == MYSQL_TYPE_BIT) ||
		    (field->type == MYSQL_TYPE_VARCHAR)) {
			std::string str;
			buffer = new ParamBuffer(str, field->length);
			_resultBind[fieldPos].buffer_type = field->type;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
		}
		else if (field->type == MYSQL_TYPE_TINY) {
			if ((field->flags & UNSIGNED_FLAG) != 0) {
				buffer = new ParamBuffer((const unsigned char) 0);
			} else {
				buffer = new ParamBuffer((const char) 0);
			}
			_resultBind[fieldPos].buffer_type = MYSQL_TYPE_TINY;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
			_resultBind[fieldPos].is_unsigned = buffer->IsUnsigned();
		}
		else if ((field->type == MYSQL_TYPE_SHORT) ||
			 (field->type == MYSQL_TYPE_YEAR)) {
			if ((field->flags & UNSIGNED_FLAG) != 0) {
				buffer = new ParamBuffer((const unsigned short int) 0);
			} else {
				buffer = new ParamBuffer((const short int) 0);
			}
			_resultBind[fieldPos].buffer_type = MYSQL_TYPE_SHORT;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
			_resultBind[fieldPos].is_unsigned = buffer->IsUnsigned();
		}
		else if ((field->type == MYSQL_TYPE_LONG) ||
			 (field->type == MYSQL_TYPE_INT24)) {
			if ((field->flags & UNSIGNED_FLAG) != 0) {
				buffer = new ParamBuffer((const unsigned int) 0);
			} else {
				buffer = new ParamBuffer((const int) 0);
			}
			_resultBind[fieldPos].buffer_type = field->type;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
			_resultBind[fieldPos].is_unsigned = buffer->IsUnsigned();
		}
		else if (field->type == MYSQL_TYPE_FLOAT) {
			_resultBind[fieldPos].buffer_type = field->type;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
			_resultBind[fieldPos].is_unsigned = buffer->IsUnsigned();
		}
		else if (field->type == MYSQL_TYPE_DOUBLE) {
			_resultBind[fieldPos].buffer_type = field->type;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
			_resultBind[fieldPos].is_unsigned = buffer->IsUnsigned();
		}
		else if ((field->type == MYSQL_TYPE_TIMESTAMP) ||
			 (field->type == MYSQL_TYPE_DATE) ||
			 (field->type == MYSQL_TYPE_TIME) ||
			 (field->type == MYSQL_TYPE_DATETIME)) {
			Julian time;
			buffer = new ParamBuffer(time);
			_resultBind[fieldPos].buffer_type = field->type;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
		}
		else if ((field->type == MYSQL_TYPE_BLOB) ||
			 (field->type == MYSQL_TYPE_TINY_BLOB) ||
			 (field->type == MYSQL_TYPE_MEDIUM_BLOB) ||
			 (field->type == MYSQL_TYPE_LONG_BLOB)) {
			_hasBlobField = true;
			Binary data(field->length);
			buffer = new ParamBuffer(data);
			_resultBind[fieldPos].buffer_type = field->type;
			_resultBind[fieldPos].buffer = buffer->Buffer();
			_resultBind[fieldPos].buffer_length = buffer->BufferSize();
			_resultBind[fieldPos].length = buffer->BufferLength();
			_resultBind[fieldPos].is_null = buffer->IsNull();
			_resultBind[fieldPos].error = buffer->Error();
		}

		if (buffer != NULL) {
			_resultParams.push_back(buffer);	
		}
		fieldPos++;
	}

	if (_resultParams.size() != _numberResultColumns) {
		mysql_free_result(metaData);
		mysql_stmt_close(_stmt);
		throw DatabaseException("Error in Statement::Prepare", 0, "----", "was not able to bind all parameters");
	}

	if (_hasBlobField) {
		my_bool setMax = 1;
		mysql_stmt_attr_set(_stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &setMax);
	}

	if (_numberResultColumns > 0) {
		if (mysql_stmt_bind_result(_stmt, _resultBind) != 0) {
			mysql_free_result(metaData);
			mysql_stmt_close(_stmt);
			throw DatabaseException(_stmt, "Error in Statement::Prepare while binding results");
		}
	}

	mysql_free_result(metaData);
}
Ejemplo n.º 18
0
int main (int argc, char *argv[]) {

    MYSQL *mysql;
    MYSQL_RES *result;
    MYSQL_ROW row;
    my_bool reconnect = 0;
    mysql = mysql_init(NULL);
    mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect);

    CONN(0);

    MYSQL_STMT    *stmt;
    MYSQL_BIND    bind[1];
    MYSQL_RES     *prepare_meta_result;
    MYSQL_TIME    ts;
    unsigned long length[1];
    int           param_count, column_count, row_count;
    short         small_data;
    int           int_data;
    char          str_data[STRING_SIZE];
    my_bool       is_null[1];

    // 1. no cursor
    stmt = mysql_stmt_init(mysql);
    mysql_stmt_prepare(stmt, SELECT_SAMPLE, strlen(SELECT_SAMPLE));
    param_count= mysql_stmt_param_count(stmt);
    //prepare_meta_result = mysql_stmt_result_metadata(stmt);
    mysql_stmt_execute(stmt);

    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= &is_null[0];
    bind[0].length= &length[0];

    mysql_stmt_bind_result(stmt, bind);
    //mysql_stmt_store_result(stmt);

    while (!mysql_stmt_fetch(stmt)) {
        printf("1 - %d \n", int_data); 
    }

    mysql_stmt_close(stmt);


    // 2. cursor read only
    stmt = mysql_stmt_init(mysql);

    unsigned long type = (unsigned long) CURSOR_TYPE_READ_ONLY;
    mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, (void*) &type);

    mysql_stmt_prepare(stmt, SELECT_SAMPLE, strlen(SELECT_SAMPLE));
    param_count= mysql_stmt_param_count(stmt);
    //prepare_meta_result = mysql_stmt_result_metadata(stmt);
    mysql_stmt_execute(stmt);

    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= &is_null[0];
    bind[0].length= &length[0];

    mysql_stmt_bind_result(stmt, bind);
    //mysql_stmt_store_result(stmt); // default 1

    while (!mysql_stmt_fetch(stmt)) {
        printf("1 - %d \n", int_data); 
    }

    mysql_stmt_close(stmt);

    // 3. set num 
    stmt = mysql_stmt_init(mysql);

    type = (unsigned long) CURSOR_TYPE_READ_ONLY;
    unsigned long prefetch_rows = 2;
    mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, (void*) &type);
    mysql_stmt_attr_set(stmt, STMT_ATTR_PREFETCH_ROWS, (void*) &prefetch_rows);

    mysql_stmt_prepare(stmt, SELECT_SAMPLE, strlen(SELECT_SAMPLE));
    param_count= mysql_stmt_param_count(stmt);
    //prepare_meta_result = mysql_stmt_result_metadata(stmt);
    mysql_stmt_execute(stmt);

    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= &is_null[0];
    bind[0].length= &length[0];

    mysql_stmt_bind_result(stmt, bind);
    //mysql_stmt_store_result(stmt);

    while (!mysql_stmt_fetch(stmt)) {
        printf("1 - %d \n", int_data); 
    }

    mysql_stmt_close(stmt);
}
Ejemplo n.º 19
0
bool CMySqlDatabase::BlobReadDb( QString &strBlobFile, QString& strSql, QString& strError )
{
    //http://www.cplusplus.com
    QByteArray byData;
    bool bRet = BlobReadDb( byData, strSql, strError );
    if ( false == bRet ) {
        return bRet;
    }

    QFile file( strBlobFile );
    bRet = file.open( QIODevice::WriteOnly );
    if ( !bRet ) {
        return bRet;
    }

    file.write( byData );
    file.close( );

    return bRet;

#if false
    MYSQL_BIND bind[ 1 ];
    ulong       length = 0;
    QByteArray byteSql;
    int nSize = 0;
    const char* pSql = NULL;
    char* bufData = NULL;
    quint32 nData = 1024 * 1024 * 2;
    int nRet = 0;
    MYSQL_RES* res = NULL;
    my_bool bGetMaxLen = 1;

    hStmt = mysql_stmt_init( &hConnect );
    bRet = ( NULL != hStmt );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto FileHandle;
    }

    byteSql = pCodec->fromUnicode( strSql );
    nSize = byteSql.count( );
    pSql = byteSql.data( );

    bRet = ( 0 == mysql_stmt_prepare( hStmt, pSql, nSize ) );
    if ( !bRet ){
        GetErrorMsg( 0, strError, false, strSql );
        goto StmtHandle;
    }

    bRet = ( 0 == mysql_stmt_execute( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto StmtHandle;
    }

    // max_allowed_packet 16M
    // write_timeout 120
    // Net Buffer 16M
    bufData = ( char* ) malloc( nData );
    memset( bind, 0, sizeof ( bind ) );
    bind[ 0 ].buffer_type = MYSQL_TYPE_LONG_BLOB;
    bind[ 0 ].length = &length; // Return Real Data Length
    bind[ 0 ].is_null = 0; /* Bind the buffers */
    bind[ 0 ].buffer = bufData; // Bind data buffer
    bind[ 0 ].buffer_length = nData; // Buffer Length

    bRet = ( 0 == mysql_stmt_bind_result( hStmt, bind ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto NewHandle;
    }

    bRet = ( 0 == mysql_stmt_attr_set( hStmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bGetMaxLen ) );
    bRet = ( 0 == mysql_stmt_store_result( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto NewHandle;
    }

    /////////////////////////////////// Get Meta Data
    res = mysql_stmt_result_metadata( hStmt );
    if ( NULL != res && 0 < res->field_count &&
        nData < res->fields[ 0 ].max_length ) {
        nData = res->fields[ 0 ].max_length; // Data Real Length
        mysql_free_result( res );

        bind[ 0 ].buffer_length = nData;
        bufData = ( char* ) realloc( bufData, nData );
        bind[ 0 ].buffer = bufData;
        bRet = ( 0 == mysql_stmt_bind_result( hStmt, bind ) );
        if ( !bRet ) {
            GetErrorMsg( 0, strError, false, strSql );
            goto NewHandle;
        }
    }
    ///////////////////////////////////

    nRet = mysql_stmt_fetch( hStmt );
    if ( MYSQL_DATA_TRUNCATED == nRet ) {
        ;
    } else {
        bRet = ( 0 == nRet );
        if ( !bRet ) {
            GetErrorMsg( 0, strError, false, strSql );
            goto NewHandle;
        }
    }

    file.write( ( const char* ) bufData, length );

    NewHandle:
    if ( NULL != bufData ) {
        free( bufData );
    }

    bRet = ( 0  == mysql_stmt_free_result( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
    }

    StmtHandle:
    bRet = ( 0 == mysql_stmt_close( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
    }

    FileHandle:
    file.close( );

    return bRet;
#endif
}
Ejemplo n.º 20
0
bool
DbUtil::runQuery(const char* sql,
                    const Properties& args,
                    SqlResultSet& rows){

  rows.clear();
  if (!isConnected())
    return false;

  g_debug << "runQuery: " << endl
          << " sql: '" << sql << "'" << endl;


  MYSQL_STMT *stmt= mysql_stmt_init(m_mysql);
  if (mysql_stmt_prepare(stmt, sql, strlen(sql)))
  {
    g_err << "Failed to prepare: " << mysql_error(m_mysql) << endl;
    return false;
  }

  uint params= mysql_stmt_param_count(stmt);
  MYSQL_BIND bind_param[params];
  bzero(bind_param, sizeof(bind_param));

  for(uint i= 0; i < mysql_stmt_param_count(stmt); i++)
  {
    BaseString name;
    name.assfmt("%d", i);
    // Parameters are named 0, 1, 2...
    if (!args.contains(name.c_str()))
    {
      g_err << "param " << i << " missing" << endl;
      assert(false);
    }
    PropertiesType t;
    Uint32 val_i;
    const char* val_s;
    args.getTypeOf(name.c_str(), &t);
    switch(t) {
    case PropertiesType_Uint32:
      args.get(name.c_str(), &val_i);
      bind_param[i].buffer_type= MYSQL_TYPE_LONG;
      bind_param[i].buffer= (char*)&val_i;
      g_debug << " param" << name.c_str() << ": " << val_i << endl;
      break;
    case PropertiesType_char:
      args.get(name.c_str(), &val_s);
      bind_param[i].buffer_type= MYSQL_TYPE_STRING;
      bind_param[i].buffer= (char*)val_s;
      bind_param[i].buffer_length= strlen(val_s);
      g_debug << " param" << name.c_str() << ": " << val_s << endl;
      break;
    default:
      assert(false);
      break;
    }
  }
  if (mysql_stmt_bind_param(stmt, bind_param))
  {
    g_err << "Failed to bind param: " << mysql_error(m_mysql) << endl;
    mysql_stmt_close(stmt);
    return false;
  }

  if (mysql_stmt_execute(stmt))
  {
    g_err << "Failed to execute: " << mysql_error(m_mysql) << endl;
    mysql_stmt_close(stmt);
    return false;
  }

  /*
    Update max_length, making it possible to know how big
    buffers to allocate
  */
  my_bool one= 1;
  mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, (void*) &one);

  if (mysql_stmt_store_result(stmt))
  {
    g_err << "Failed to store result: " << mysql_error(m_mysql) << endl;
    mysql_stmt_close(stmt);
    return false;
  }

  uint row= 0;
  MYSQL_RES* res= mysql_stmt_result_metadata(stmt);
  if (res != NULL)
  {
    MYSQL_FIELD *fields= mysql_fetch_fields(res);
    uint num_fields= mysql_num_fields(res);
    MYSQL_BIND bind_result[num_fields];
    bzero(bind_result, sizeof(bind_result));

    for (uint i= 0; i < num_fields; i++)
    {
      if (is_int_type(fields[i].type)){
        bind_result[i].buffer_type= MYSQL_TYPE_LONG;
        bind_result[i].buffer= malloc(sizeof(int));
      }
      else
      {
        uint max_length= fields[i].max_length + 1;
        bind_result[i].buffer_type= MYSQL_TYPE_STRING;
        bind_result[i].buffer= malloc(max_length);
        bind_result[i].buffer_length= max_length;
      }
    }

    if (mysql_stmt_bind_result(stmt, bind_result)){
      g_err << "Failed to bind result: " << mysql_error(m_mysql) << endl;
      mysql_stmt_close(stmt);
      return false;
    }

    while (mysql_stmt_fetch(stmt) != MYSQL_NO_DATA)
    {
      Properties curr(true);
      for (uint i= 0; i < num_fields; i++){
        if (is_int_type(fields[i].type))
          curr.put(fields[i].name, *(int*)bind_result[i].buffer);
        else
          curr.put(fields[i].name, (char*)bind_result[i].buffer);
      }
      rows.put("row", row++, &curr);
    }

    mysql_free_result(res);

    for (uint i= 0; i < num_fields; i++)
      free(bind_result[i].buffer);

  }

  // Save stats in result set
  rows.put("rows", row);
  rows.put("affected_rows", mysql_affected_rows(m_mysql));
  rows.put("mysql_errno", mysql_errno(m_mysql));
  rows.put("mysql_error", mysql_error(m_mysql));
  rows.put("mysql_sqlstate", mysql_sqlstate(m_mysql));
  rows.put("insert_id", mysql_insert_id(m_mysql));

  mysql_stmt_close(stmt);
  return true;
}
Ejemplo n.º 21
0
int sqlite3_prepare(sqlite3* db,              /* Database handle */
                    const char* zSql,         /* SQL statement, UTF-8 encoded */
                    int nBytes,               /* Maximum length of zSql in bytes. */
                    mysqlite3_stmt** ppStmt,  /* OUT: Statement handle */
                    const char** pzTail       /* OUT: Pointer to unused portion of zSql */
)
{
    int rc = SQLITE_OK;
    
    mysqlite3_stmt* stmt = (mysqlite3_stmt*)malloc(sizeof(mysqlite3_stmt));
    
    stmt->mydb   = db;
    stmt->mystmt = mysql_stmt_init(db);
    stmt->myres  = NULL;
    stmt->myparams = NULL;
    stmt->results  = NULL;
    stmt->nresults = 0;
    stmt->executed = 0;
    stmt->nrow     = 0;
    stmt->lengths  = NULL;
    
    int stmt_len = statement_length(zSql, nBytes);
    
    if (nBytes > 0 && nBytes < stmt_len)
    {
        stmt_len = nBytes;
    }
    
    // "Strip" trailing semicolon, if present
    if (zSql[stmt_len-1] == ';')
    {
        stmt_len -= 1;
    }
    
    // Make a copy of the SQL and save it
    stmt->sql = strndup(zSql, stmt_len);
    
    mysql_stmt_prepare(stmt->mystmt, stmt->sql, stmt_len);
    
    stmt->nparams = mysql_stmt_param_count(stmt->mystmt);
    if (stmt->nparams > 0)
    {
        stmt->myparams = (MYSQL_BIND*)malloc(sizeof(MYSQL_BIND)*stmt->nparams);
    }
    
    /* Result set information */
    stmt->myres = mysql_stmt_result_metadata(stmt->mystmt);

    stmt->ncolumns = 0;
    if (stmt->myres)
    {
        /* Get total columns in the query */
        stmt->ncolumns = mysql_num_fields(stmt->myres);
        
        // Set STMT_ATTR_UPDATE_MAX_LENGTH attribute
        my_bool aBool = 1;
        mysql_stmt_attr_set(stmt->mystmt, STMT_ATTR_UPDATE_MAX_LENGTH, &aBool);
        
        if (stmt->ncolumns > 0)
        {
            stmt->results = malloc(sizeof(MYSQL_BIND)* stmt->ncolumns);
            stmt->lengths = malloc(sizeof(unsigned long)* stmt->ncolumns);
            memset(stmt->results, 0, sizeof(MYSQL_BIND)* stmt->ncolumns);
            
            int i;
            for (i=0; i < stmt->ncolumns; i++)
            {
                //stmt->results[i].buffer          = malloc(stmt->myres->fields[i].max_length);
                //stmt->results[i].buffer_type     = stmt->myres->fields[i].type;
                //stmt->results[i].buffer_length   = stmt->myres->fields[i].max_length;
                
                stmt->results[i].buffer          = 0;
                stmt->results[i].is_null         = 0;
                stmt->results[i].buffer_length   = 0;
                stmt->results[i].length          = &stmt->lengths[i];
            }
        }
    }
    
    *ppStmt = (mysqlite3_stmt*)stmt;
    
    if (pzTail)
    {
        (*pzTail) = NULL;
        if (stmt_len < strlen(zSql))
        {
            (*pzTail) = zSql+stmt_len;
            if (*pzTail[0] == ';') {
                (*pzTail)++;
            }
            if (*pzTail[0] == '\0') {
                *pzTail = NULL;
            }
        }
    }
    
    return rc;
};