Last active
December 17, 2015 20:18
-
-
Save sgielen/5666189 to your computer and use it in GitHub Desktop.
librusql-voorbeeldcode voor in libvreemd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
std::string url = "unix:///tmp/mysql.sock"; | |
std::string user = "root"; | |
std::string pass = ""; | |
std::string database = "foo"; | |
rusql::connection c; | |
try { | |
c = rusql::connection(url, user, pass, database); | |
} catch(rusql::sql_connection_error &e) { | |
std::cerr << "Database connection error: " << e.what() << std::endl; | |
return; | |
} | |
//// STANDARD USE | |
try { | |
rusql::statement s = c.prepare("SELECT * FROM info WHERE id=?"); | |
rusql::resultset rs = s.execute(6); | |
for(auto it = rs.begin(); it != rs.end(); ++it) { | |
std::cout << "Row from the info table: " << *it << std::endl; | |
} | |
} catch(rusql::sql_statement_error &e) { | |
std::cerr << "Statement error: " << e.what() << std::endl; | |
} | |
///// TABLE LOCKING //// | |
// when tables are locked, only those tables may be used. When the rusql::lock is destructed, | |
// an UNLOCK TABLES is done, so all tables can be used again. | |
try { | |
rusql::lock tables = c.lock_tables({"read" => ["info"], "write" => ["foo", "bar"]}); | |
rusql::statement read = c.prepare("SELECT * FROM info WHERE id=?"); | |
rusql::statement write = c.prepare("INSERT INTO foo SET value=? WHERE info_id=?") | |
rusql::resultset rs = read.execute(5); | |
for(auto it = rs.begin(); it != rs.end(); ++it) { | |
std::string info_value = it->get("value"); | |
int info_id = it->get("id"); | |
try { | |
write.execute(info_value, info_id); | |
} catch(rusql::sql_statement_error &e) { | |
std::cerr << "Foo write error: " << e.what() << std::endl; | |
} | |
} | |
} catch(rusql::sql_statement_error &e) { | |
std::cerr << "Info read error: " << e.what() << std::endl; | |
} | |
///// TRANSACTIONS ///// | |
// 1 to 1 ratio between two tables; we want to remove a row from both tables | |
// without invalidating the database schema. Therefore, use transactions and | |
// finally do an atomic commit. | |
try { | |
rusql::transaction t = c.start_transaction(); | |
rusql::statement a = c.prepare("DELETE FROM a WHERE id=?"); | |
rusql::statement b = c.prepare("DELETE FROM b WHERE id=?"); | |
rusql::statement s = c.prepare("SELECT id FROM a_and_b WHERE years > 85"); | |
rusql::resultset rs = s.execute(); | |
for(auto it = rs.begin(); it != rs.end(); ++it) { | |
a.execute(it->get("id")); | |
b.execute(it->get("id")); | |
} | |
t.commit(); | |
} catch(rusql::sql_statement_error &e) { | |
std::cerr << "Transaction aborted because of error: " << e.what() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment