使用 C 连接到 MySQL 数据库
为了建立与 MySQL 数据库的连接并执行查询,C 提供了全面的解决方案。让我们探讨如何高效地完成此任务。
所需的库
首先将必要的库合并到您的 C 项目中:
示例代码
以下示例代码演示了如何建立连接,执行查询,并从 MySQL 数据库检索结果:
<code class="c++">#include <stdlib.h> #include <iostream> #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; int main() { try { // Create the necessary objects sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; // Establish a connection driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); // Set the default schema con->setSchema("test"); // Create a statement object stmt = con->createStatement(); // Execute a query res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // Replace with your statement // Iterate over the results while (res->next()) { cout << "\t... MySQL replies: "; // Access column data by alias or column name cout << res->getString("_message") << endl; cout << "\t... MySQL says it again: "; // Access column data by numeric offset (1-based) cout << res->getString(1) << endl; } // Clean up resources delete res; delete stmt; delete con; } catch (sql::SQLException &e) { // Handle exceptions cout << "# ERR: SQLException in " << __FILE__ << " (" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )" << endl; } return EXIT_SUCCESS; }</code>
结论
按照以下步骤并结合提供的代码示例,您可以成功连接到从 C 语言创建您的 MySQL 数据库,执行查询并检索所需的结果。这使您能够开发健壮且高效的数据库驱动应用程序。
以上是如何使用 C 连接到 MySQL 数据库?的详细内容。更多信息请关注PHP中文网其他相关文章!