如何使用 C 连接到 MySQL 数据库
在您的网站和 MySQL 数据库之间建立连接,并在上执行选择查询表行,您需要利用适当的 C 库。以下是实现此目标的方法:
导入以下库:
<code class="cpp">#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;</code>
设置您的 C 程序:
<code class="cpp">int main(void) { // Initialize connection details sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; try { // Establish connection to MySQL driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); con->setSchema("test"); // Replace "test" with your database name // Create statement object stmt = con->createStatement(); // Execute select query res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // Display query results while (res->next()) { cout << "\t... MySQL replies: " << res->getString("_message") << endl; cout << "\t... MySQL says it again: " << res->getString(1) << endl; } // Clean up resources delete res; delete stmt; delete con; } catch (sql::SQLException &e) { // Handle database exception cout << "# ERR: SQLException in " << __FILE__ << endl; cout << "# ERR: " << e.what() << endl; } return EXIT_SUCCESS; }</code>
通过使用库并按照以下步骤操作如上所述,您可以使用 C 成功连接到 MySQL 数据库并对表行执行选择查询。
以上是如何使用 C 连接到 MySQL 数据库并执行查询?的详细内容。更多信息请关注PHP中文网其他相关文章!