
There are those times when you need to retrieve the highest used auto increment value for a table. The following c++ snippet offers solution.
[codesyntax lang=”cpp”]
long Glr(string usr, string pwd, std::string dbname, std::string tabname) { sql::Connection *con; sql::Driver * driver; driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", usr, pwd); sql::ResultSet* rres; sql::Statement * stmt; con->setSchema(dbname); stmt = con->createStatement(); rres = stmt->executeQuery( "SELECT `id` from " + tabname + " Order By `id` DESC limit 1"); rres->next(); long retVal = rres->getInt64("id"); delete rres; delete stmt; delete con; return retVal; }
[/codesyntax]
To invoke the function use the following calling sequence.
[codesyntax lang=”cpp”]
long lr = Glr("UserID", "Password", "DatabaseName", "TableName");
[/codesyntax]
This section of code will retrieve the highest value for auto increment of any table in MySQL.
To keep this example precise the try catch blocks and error handling are omitted. Those blocks are recommended for any production type environment.
Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.