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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
#include <iostream> #include <sqlite3.h> using namespace std; class Database { public: Database(const string& dbName); ~Database(); void createTable(); void insertData(const string& playerName, int score); void displayData(); private: sqlite3* db; string dbName; static int callback(void* NotUsed, int argc, char** argv, char** azColName); void executeSQL(const string& sql); }; Database::Database(const string& dbName) : db(nullptr), dbName(dbName) { if (sqlite3_open(dbName.c_str(), &db)) { cerr << "Can't open database: " << sqlite3_errmsg(db) << endl; exit(1); } else { cout << "Opened database successfully" << endl; } } Database::~Database() { if (db) { sqlite3_close(db); cout << "Closed database successfully" << endl; } } void Database::createTable() { string sql = "CREATE TABLE IF NOT EXISTS SCORES(" "ID INTEGER PRIMARY KEY AUTOINCREMENT," "PLAYER_NAME TEXT NOT NULL," "SCORE INT NOT NULL);"; executeSQL(sql); cout << "Table created successfully" << endl; } void Database::insertData(const string& playerName, int score) { string sql = "INSERT INTO SCORES (PLAYER_NAME, SCORE) VALUES ('" + playerName + "', " + to_string(score) + ");"; executeSQL(sql); cout << "Data inserted successfully" << endl; } void Database::displayData() { string sql = "SELECT * FROM SCORES;"; executeSQL(sql); } int Database::callback(void* NotUsed, int argc, char** argv, char** azColName) { for (int i = 0; i < argc; i++) { cout << azColName[i] << ": " << (argv[i] ? argv[i] : "NULL") << endl; } cout << endl; return 0; } void Database::executeSQL(const string& sql) { char* errMsg = 0; int rc = sqlite3_exec(db, sql.c_str(), callback, 0, &errMsg); if (rc != SQLITE_OK) { cerr << "SQL error: " << errMsg << endl; sqlite3_free(errMsg); } } int main() { Database db("game_scores.db"); db.createTable(); db.insertData("Player1", 100); db.insertData("Player2", 150); db.insertData("Player3", 200); cout << "Displaying data:" << endl; db.displayData(); return 0; } |
Explanation:
- SQLite3 Integration:
- The program uses the SQLite3 library to handle database operations. Make sure to link the SQLite library during compilation (e.g.,
-lsqlite3
Advertisement
- The program uses the SQLite3 library to handle database operations. Make sure to link the SQLite library during compilation (e.g.,
- Database Class:
- The
Database
class encapsulates all the SQLite-related functionality, including connecting to the database, creating tables, inserting data, and retrieving data.
- The
- Constructor & Destructor:
- The constructor opens the SQLite database specified by
dbName
. If the database does not exist, SQLite creates it. - The destructor ensures the database connection is closed properly when the
Database
object is destroyed.
Advertisement - The constructor opens the SQLite database specified by
- Create Table:
- The
createTable
method creates aSCORES
table if it doesn’t already exist. The table has three columns:ID
(an auto-incrementing primary key),PLAYER_NAME
(a string), andSCORE
(an integer).
- The
- Insert Data:
- The
insertData
method inserts a new player’s name and score into theSCORES
table. It constructs an SQLINSERT
statement using the provided data and executes it.
- The
- Display Data:
- The
displayData
method retrieves all records from theSCORES
table and displays them. It executes aSELECT
statement and uses a callback function to handle the results.
- The
- Callback Function:
- The static
callback
function is used by SQLite to process the results of aSELECT
Advertisement
- The static
- Main Function:
- The
main
function demonstrates how to use theDatabase
class. It creates a database, creates theSCORES
table, inserts some sample data, and displays the stored data.
- The
Possible Enhancements:
- Parameterized Queries: Use prepared statements to avoid SQL injection and improve performance.
- Error Handling: Enhance error handling to manage more complex scenarios.
- Dynamic Input: Allow users to input data dynamically instead of hardcoding values.
- Extend Functionality: Add features like updating scores, deleting records, or querying specific data.