2017-01-01 73 views
-3

我正在編寫一些使用MySQL api創建數據庫,插入,更新等的C代碼。我在查找MySQL語法後查找最簡潔/正確的方法來構建查詢時遇到了一些麻煩可能會非常棘手擺在AC字符串,例如,我想查詢看起來像這樣的可讀性:c字符串文字中的特殊字符

strcpy(query, "CREATE TABLE Users (
        userID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (userID), 
        email VARCHAR(31) NOT NULL, 
        timeEntered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 
        address  VARCHAR(31) NOT NULL, 
        index (email)) 
       "); 

那麼當然我會跑的東西查詢類似

/* send SQL query */ 
    if (mysql_query(conn, query)) { 
     fprintf(stderr, "%s\n", mysql_error(conn)); 
     exit(1); 
    } else { printf("table created\n"); } 

然而,編譯器抱怨預期')'和丟失終止「等等。是最好的解決方案?

回答

1

C字符串文字不能包含換行符。你可以這樣做,但:

strcpy(query, "CREATE TABLE Users (" 
       "userID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (userID), " 
       "email VARCHAR(31) NOT NULL, " 
       "timeEntered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " 
       "address  VARCHAR(31) NOT NULL, " 
       "index (email))"); 

這將創建一個字符串從相鄰的字符串字面常量。

+0

添加的細節「不能包含換行符」 - >字符串常量可以包含源字符的任何成員設置除雙引號「,反斜線\或換行符」 – chux

3

爲了提高可讀性,我建議你使用C89的字符串連接特點:

strcpy(query, "CREATE TABLE Users (" 
       "userID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (userID)," 
       "email VARCHAR(31) NOT NULL," 
       "timeEntered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," 
       "address  VARCHAR(31) NOT NULL," 
       "index (email))" 
); 

只需使用多達空格分開,你需要的可讀性字符串文字的序列。

輸入K & R C的昔日,只有這樣的反斜槓換行方式:

puts("A very\ 
long string\ 
literal spanning\ 
several lines"); 
1

C++編譯器通常不支持多行字符串常量,因爲我認爲它可能不同於編譯器和編譯器以及它們符合的標準級別。

它的安全它分成幾個字符串沒有任何分隔,這是由任何編譯器理解:

strcpy(query, "CREATE TABLE Users (" 
      " userID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (userID)," 
      " email VARCHAR(31) NOT NULL," 
      " timeEntered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," 
      " address  VARCHAR(31) NOT NULL," 
      " index (email))" 
      );