CGI如何用C控制SQLite3?

來源:互聯網
上載者:User

【問題描述】利用C編寫CGI程式,如何控制SQLite3,進行基本的資料庫操作?

【簡介】

需要建立的變數

  1. sqlite3 *db;  
  2. int nrow = 0, ncolumn = 0;  
  3. char **azResult = NULL;  
  4. char *zErrMsg = 0;  
  5.       
  6. char sql[500];  
  7. int rc = 0;  

需要包含的標頭檔

  1. #include <sqlite3.h>  

備忘:詳見搭建SQLite3嵌入式開發環境 (),安裝後,會產生一個sqlite3.h的檔案。

1 開啟資料庫(open)

  1. rc = sqlite3_open("test.db", &db);  
  2. if (rc)  
  3. {  
  4.     printf("Content-type: text/html\n\n");  
  5.     fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));  
  6.     sqlite3_close(db);  
  7.     return sql_errror();  
  8. }  

其中,sql_error()是自訂的函數。
2 關閉資料庫(close)

  1. sqlite3_close(db);  

3 查(select)

  1. sprintf(sql,   
  2.     "select * from user where name='%s' AND passwd='%s'",   
  3.     username, passwd);    
  4.   
  5. rc = sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );  
  6. if (rc != SQLITE_OK)  
  7. {  
  8.     printf("Content-type: text/html\n\n");  
  9.     fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  10.     sqlite3_close(db);  
  11.     return sql_errror();  
  12.  }  
  13.   
  14. if(*azResult != NULL)  
  15. {  
  16.     printf("Content-type: text/html\n\n");  
  17.     int i;  
  18.     for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )  
  19.         printf( "azResult[%d] = %s\n", i , azResult[i] );  
  20.     ...  
  21. }     

查詢的結果儲存在**azResult中,為nrow x ncolumn數組。

4 增(insert)

  1. sprintf(sql,   
  2.     "insert into user(name,passwd) values('%s','%s')",   
  3.     username,passwd);  
  4.   
  5. rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);  
  6. if (rc != SQLITE_OK)  
  7. {  
  8.     fprintf(stderr, "SQL1 error: %s\n", zErrMsg);  
  9.     return 1;  
  10. }  

回呼函數(callback)

  1. static int callback(void *NotUsed, int argc, char **argv, char **azColName)  
  2. {  
  3.     int i = 0;  
  4.   
  5.     printf("Content-type: text/html\n\n");  
  6.     for (i=0; i<argc; i++)  
  7.     {      
  8.         printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");  
  9.     }  
  10.   
  11.     printf("\n");  
  12.     return 0;  
  13. }  
  • 1
  • 2
  • 下一頁

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.