在sqlite Swift中将数组作为参数传递

时间:2015-01-08 16:21:36

标签: swift sqlite

我在我的#import <sqlite3.h>文件和header.h中添加了libsqlite3.dylib,在我的项目中实现了Sqlite。

如何将数组作为参数传递给我的查询,这是我的想法:

var arrayId = [1,2] // array with interested Id 
var query:NSString = "Select id from Product where id IN \(arrayId)" // I want to select Products with id that are in the array

修改: 如果arrayId是NSArray,它会改变吗?因为我还需要arrayId作为NSArray。

然后我继续打开sqlite数据库,准备查询等等。

提前谢谢。

5 个答案:

答案 0 :(得分:4)

您可以轻松地将数组合并为具有连接功能的字符串。

var arrayId = [1,2] // array with interested Id
var inExpression = ",".join(map(arrayId) { "\($0)"})
// inExpression = "1,2"
var query = "Select id from Product where id IN (\(inExpression))"

答案 1 :(得分:1)

使用Swift自己的字符串插值来创建SQL语句可能存在风险(与任何语言一样)。 sqlite3库为此提供了参数绑定:

if (statement.prepare("SELECT name FROM products WHERE id = ?") != .Ok) {
    // Deal with error here
}

// Bind the question mark to your value
statement.bindInt(1, value: 8766)

if (statement.step() == .Row) {
    let name = statement.getStringAt(1)
    // ...do something with your data from the statement
}

// Done.
statement.finalizeStatement()

编辑:

对于下面的评论,您需要()括号,而不是[]:

select id, body from test where id in (1,2);

select id, body from test where id in [1,2];

答案 2 :(得分:1)

Swift3的更新:

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "iteratorG.h"
#include "positiveIntType.h"
#include "stringType.h" 

#define MAXARRAY 5

/* Helper Functions Below */

/* Returns 1 if marks >= 50, 0 otherwise  */
int passMarks(void *marks){
  return (*((int *) marks) >= 50); 

  /* Easy to understand below .. 
     int *ip = (int *) marks;
     if(*ip >= 50) { return 1; }
     else { return 0; } 
  */
}

/* Returns 1 if str starts with "jo" */
int prefixJo(void *str){
  return (strncmp("jo", (char *) str, 2) == 0) ; 
}

/* A function to print a string from a void pointer */
void prnStr(void *vp){
  assert(vp != NULL);
  printf(" %s", (char *) vp );      
}

/* A function to print an integer from a void pointer */
void prnInt(void *vp){
  assert(vp != NULL);
  printf(" %d", *((int *) vp) );    
}

/* Prints previous element using the given function 'fp'
   examples: prnPrev(it1, prnInt); prnPrev(it2, prnStr);
*/
void prnPrev(IteratorG it, void (*fp) (void *p) ){
  void *prevP = previous(it);
  assert(prevP != NULL);
  printf("> Previous value is: "); 
  fp(prevP);
  printf("\n"); 
}

/* Prints next element using the given function 'fp'
   examples:   prnNext(it1, prnInt); prnNext(it2, prnStr);
*/
void prnNext(IteratorG it, void (*fp) (void *p) ){
  void *nextP = next(it);
  assert(nextP != NULL);
  printf("> Next value is: "); 
  fp(nextP);
  printf("\n"); 
}

/* Prints elements of 'it' from current to last position 
   using the given function 'fp'. The current position 
   of 'it' will change to the end of the list.
   examples: prnIt(it1, prnInt); prnIt(it2, prnStr);
*/
void prnIt(IteratorG it, void (*fp) (void *p) ){
  int count = 0;
  while(hasNext(it)){
    void *nextP = next(it); 
    count++;
    if(count > 1) { printf(", "); }
    fp(nextP);      
  }
  printf("\n"); 
}


/* Few Tests Below  */

void test1(){
  printf("\n--====  Test-01       ====------\n");
  IteratorG it1 = newIterator(positiveIntCompare, positiveIntNew,  positiveIntFree);
  int a[MAXARRAY] = { 25, 78, 6, 82 , 11};
  for(int i=0; i<MAXARRAY; i++){
    int result = add(it1 , &a[i]); 
    printf("> Inserting %d: %s \n", a[i], (result==1 ? "Success" : "Failed") );
  }
  freeIt(it1);
  printf("--====  End of Test-01 ====------\n");
}

void test2(){
  printf("\n--====  Test-02       ====------\n");
  IteratorG it1 = newIterator(positiveIntCompare, positiveIntNew, positiveIntFree);
  int a[MAXARRAY] = { 72, 14, 62, 8, 93};
  for(int i=0; i<MAXARRAY; i++){
    int result = add(it1 , &a[i]); 
    printf("> Inserting %d: %s \n", a[i], (result==1 ? "Success" : "Failed") );
  }

  prnNext(it1, prnInt);
  prnNext(it1, prnInt);
  prnPrev(it1, prnInt);

  int newVal1 = 55;
  int result1 = set(it1, &newVal1);
  printf("> Set value: %d ; return val: %d \n", newVal1,  result1 );  

  prnPrev(it1, prnInt);

  freeIt(it1);
  printf("--====  End of Test-02 ====------\n");
}

void test3(){
  printf("\n--====  Test-03       ====------\n");
  IteratorG it1 = newIterator(positiveIntCompare, positiveIntNew, positiveIntFree);
  int a[MAXARRAY] = { 04, 54, 15, 12, 34};
  for(int i=0; i<MAXARRAY; i++){
    int result = add(it1 , &a[i]); 
    printf("> Inserting %d: %s \n", a[i], (result==1 ? "Success" : "Failed") );
  }

  reset(it1);
  printf("> it1 (after reset): \n");
  prnIt(it1, prnInt);
  reset(it1);

  IteratorG advIt1 = advance(it1, 4);
  printf("> advance(it1, 4) returns: \n");
  prnIt(advIt1, prnInt);

  //IteratorG advIt2 = advance(it1, -3);
  //printf("> advance(it1, -3) returns: \n");
  //prnIt(advIt2, prnInt);

  //printf("> In 'it1', ");
  //prnPrev(it1, prnInt);

  freeIt(it1);
  //freeIt(advIt1);
  //freeIt(advIt2);

  printf("--====  End of Test-03 ====------\n");
}    

int main(int argc, char *argv[])
{


  test1();
  test2();
  test3();
  return EXIT_SUCCESS;

}

答案 3 :(得分:0)

你需要完成两件事:将Int的数组转换为String,然后将数组内置到一个字符串中,方法是用逗号连接它们(正如你想要的那样) IN SQL语句)。

这是一个基本功能就是这样:

func implode(ints: [Int]) -> String {
    // Convert to Strings
    let strs = ints.map { String($0) }
    // Join Strings with commas
    return ",".join(strs)
}

然后使用:

"WHERE id IN (\(implode(arrayId)))"

答案 4 :(得分:0)

我可能会使用类似的东西:

var arrayId = [1,2] // array with interested Id
var str = ",".join(arrayId.map { return "\($0)" })
var query = "SELECT id FROM Product WHERE id IN [\(str)]"