Skip to content

Instantly share code, notes, and snippets.

@Ratstail91
Created May 5, 2014 12:05
Show Gist options
  • Save Ratstail91/a1facb724de18afc08ed to your computer and use it in GitHub Desktop.
Save Ratstail91/a1facb724de18afc08ed to your computer and use it in GitHub Desktop.
Me familiarizing myself with SQL. Good god this shit is irritating.
#include "sqlite3/sqlite3.h"
#include <iostream>
#include <string>
using namespace std;
const char* command = "CREATE TABLE accounts(username VARCHAR(100)); INSERT INTO accounts VALUES(\"Ratstail91\"); SELECT * FROM accounts;";
int main(int argc, char* argv[]) {
//the variables
sqlite3* db = nullptr;
sqlite3_stmt* statement = nullptr;
const char* cmd = command;
int ret = 0;
//open the database connection
if ((ret = sqlite3_open_v2("database.db", &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, nullptr)) != SQLITE_OK) {
cerr << "Could not open a database connection" << endl;
return ret;
}
while (*cmd) {
if ((ret = sqlite3_prepare_v2(db, cmd, -1, &statement, &cmd)) != SQLITE_OK) {
cerr << "Failed to prepare the SQL statement" << endl;
return ret;
}
while((ret = sqlite3_step(statement)) == SQLITE_ROW) {
cout << sqlite3_column_text(statement, 0) << endl;
}
if (ret != SQLITE_DONE) {
cerr << "Unknown error occurred" << endl;
return ret;
}
sqlite3_finalize(statement);
}
//prep
cmd = "INSERT INTO accounts VALUES(?);";
if ((ret = sqlite3_prepare_v2(db, cmd, -1, &statement, &cmd)) != SQLITE_OK) {
cerr << "Failed to prepare the parameter statement" << endl;
return ret;
}
//replace the parameter
if ((ret = sqlite3_bind_text(statement, 1, "Kayne Ruse", 11, SQLITE_STATIC)) != SQLITE_OK) {
cerr << "Failed to replace the parameter" << endl;
return ret;
}
//execut this final query
if ((ret = sqlite3_step(statement)) != SQLITE_DONE) {
cerr << "Failed to execute the final statement" << endl;
return ret;
}
sqlite3_finalize(statement);
sqlite3_close(db);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment