Connecting to a MySQL database from a C application allows you to perform database operations, such as executing SQL queries. Here's a guide on how to do it:
Prerequisites:
Steps:
Include Necessary Headers:
<code class="cpp">#include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h></code>
Create a Connection:
<code class="cpp">sql::Driver *driver = get_driver_instance(); sql::Connection *con = driver->connect("tcp://127.0.0.1:3306", "root", "root");</code>
Set the Database:
<code class="cpp">con->setSchema("your_database_name");</code>
Create a Statement and Query:
<code class="cpp">sql::Statement *stmt = con->createStatement(); sql::ResultSet *res = stmt->executeQuery("your_sql_query");</code>
Iterate Over Results:
<code class="cpp">while (res->next()) { cout << res->getString("column_name") << endl; }
Here's an example that demonstrates how to execute a simple "Hello World!" query:
<code class="cpp">int main() { sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; try { con = get_driver_instance()->connect( "tcp://127.0.0.1:3306", "user", "password"); con->setSchema("test"); stmt = con->createStatement(); res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); while (res->next()) { cout << "MySQL replies: " << res->getString("_message") << endl; } } catch (sql::SQLException &e) { cout << "MySQL error code: " << e.getErrorCode() << endl; } return 0; }</code>
By following these steps, you can connect to a MySQL database and execute SQL queries using C .
The above is the detailed content of How to Connect to a MySQL Database from Your C Application?. For more information, please follow other related articles on the PHP Chinese website!