2015-11-03 97 views
0

如何修復這個錯誤SQLite數據庫與C/C++

/home/andi/Desktop/latihan/sqlite c++/sqlite insert.cpp:37:76: error: invalid operands of types ‘const char [53]’ and ‘char [50]’ to binary ‘operator+’

這是代碼。我希望我的代碼可讀,對不起我的可憐英語

# include <stdio.h> 
# include <iostream> 
# include <sqlite3.h> 
# include <stdlib.h> 
using namespace std; 
int main(void) 
{ 
sqlite3 *conn; 
sqlite3_stmt *res; 
int  error = 0; 
int  rec_count = 0; 
const char  *errMSG; 
const char  *tail; 
char sql_lite[900]=" "; 
int x,number; 
char name[50]; 
char username[50]; 
char password[50]; 
error = sqlite3_open("data.dat", &conn); 
if (error) 
{ 
printf("Can not open database"); 

} 


printf("Enter the number of data to be inserted\n"); 
scanf("%d",&x); 

for(number=x;number>0;number--) 
{ 
cout<<"name : ";cin>>name; 
cout<<"username : ";cin>>username; 
cout<<"password : ";cin>>password; 
} 

sprintf(sql_lite, "INSERT INTO login (name,username,password) VALUES ('"+ username + "','" + name + "','" + password +"');"); 
error = sqlite3_exec(conn, sql_lite, 0, 0, 0); 
error = sqlite3_prepare_v2(conn, "SELECT * FROM login order by No",1000, &res, &tail); 


if (error != SQLITE_OK) 
{ 
printf("We did not get any data!"); 
exit(0); 

} 

printf("=======================================\n"); 

while (sqlite3_step(res) == SQLITE_ROW) 
{ 
printf("%d|", sqlite3_column_int(res, 0)); 
printf("%s|", sqlite3_column_text(res, 1)); 
printf("%s|", sqlite3_column_text(res, 2)); 
printf("%s|", sqlite3_column_text(res, 3)); 
printf("%u\n", sqlite3_column_int(res, 4)); 


rec_count++; 
} 

printf("=======================================\n"); 
printf("We received %d records.\nTotal rows=%d\n",rec_count,SQLITE_ROW); 

sqlite3_finalize(res); 

sqlite3_close(conn); 

return 0; 
} 

回答

0

這裏的問題不是關於SQL。 對於char數組級聯,不能使用+運算符。爲此,您必須使用sprintf。看到這個例子

char buffer [50]; 
    char* a="aaaa", b="bbbbbbb"; 
    sprintf (buffer, "%s plus %s , a, b); 

但我建議你使用的std::string代替char數組,如果你在C++編程。

如何使用字符串

#include <iostream> 
#include <string> 
int main() 
{ 

    std::string name="",username="",password=""; 

    std::cout << "name : "; std::cin >> name; 
    std::cout << "username : "; std::cin >> username; 
    std::cout << "password : "; std::cin >> password; 

    std::string query = "INSERT INTO login (name,username,password) VALUES ('" + username + "','" + name + "','" + password + "');"; 
    std::cout << query << std::endl; 
    return 0; 
} 
+0

感謝回答我的問題.. –

+0

,但你可以舉一些例子說明了使用字符串,,我還是搞不清 –

+0

非常感謝nayana ,,非常有幫助 –