1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <stdio.h> #include "sqlite3.h"
#ifdef _WIN32 #include <windows.h> #endif
int main(int argc, char **argv) { #ifdef _WIN32 SetConsoleOutputCP(CP_UTF8); #endif const char *dbfile = (argc > 1) ? argv[1] : "Chinook_Sqlite.sqlite"; sqlite3 *db; sqlite3_stmt *stmt; int rc;
rc = sqlite3_open(dbfile, &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db)); return 1; } printf("Opened database: %s\n\n", dbfile);
const char *sql1 = "SELECT ArtistId, Name FROM Artist LIMIT 10;"; rc = sqlite3_prepare_v2(db, sql1, -1, &stmt, NULL); if (rc != SQLITE_OK) { fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } printf("--- 前10个艺术家 ---\n"); while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { int id = sqlite3_column_int(stmt, 0); const unsigned char *name = sqlite3_column_text(stmt, 1); printf("ArtistId=%d, Name=%s\n", id, name ? (const char *)name : "NULL"); } sqlite3_finalize(stmt);
const char *sql2 = "SELECT Artist.Name, COUNT(Album.AlbumId) AS AlbumCount " "FROM Artist JOIN Album ON Artist.ArtistId = Album.ArtistId " "GROUP BY Artist.ArtistId " "ORDER BY AlbumCount DESC " "LIMIT 10;"; rc = sqlite3_prepare_v2(db, sql2, -1, &stmt, NULL); if (rc != SQLITE_OK) { fprintf(stderr, "Prepare failed: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } printf("\n--- 每位艺术家的专辑数量(前10) ---\n"); while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { const unsigned char *name = sqlite3_column_text(stmt, 0); int count = sqlite3_column_int(stmt, 1); printf("%s: %d\n", name ? (const char *)name : "NULL", count); } sqlite3_finalize(stmt);
sqlite3_close(db); printf("\nClosed database.\n"); return 0; }
|