從 C 應用程式連接到 MySQL 資料庫可讓您執行資料庫操作,例如執行 SQL 查詢。以下是如何操作的指南:
先決條件:
步驟:
包含必要的標頭:
<code class="cpp">#include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h></code>
<code class="cpp">sql::Driver *driver = get_driver_instance(); sql::Connection *con = driver->connect("tcp://127.0.0.1:3306", "root", "root");</code>
<code class="cpp">con->setSchema("your_database_name");</code>
<code class="cpp">sql::Statement *stmt = con->createStatement(); sql::ResultSet *res = stmt->executeQuery("your_sql_query");</code>
<code class="cpp">while (res->next()) { cout << res->getString("column_name") << endl; }
<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>
以上是如何從 C 應用程式連接到 MySQL 資料庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!