Cin in C can be combined with the database through a database interface library (such as MySQL Connector/C or ODBC). Specific steps include: installing the database interface library; establishing a database connection; creating a query statement; binding the cin input to the query parameters; executing the query; and obtaining the query results.
The combination of cin and database in C
Use cin in C to read user input from the command line. And database is used to store and manage data. To combine cin with a database, you need to use a database interface library (such as MySQL Connector/C or ODBC).
Using MySQL Connector/C
Include necessary header files in your C code.
#include <iostream> #include <mysqlx/xdevapi.h>
Establish a database connection.
mysqlx::Session session("host", "port", "user", "password", "database");
Create query statement.
std::string query = "SELECT * FROM table_name WHERE column_name = ?";
Bind cin input to query parameters.
mysqlx::PreparedStatement stmt = session.prepare(query); std::string input; std::cin >> input; stmt.bind("column_name", input);
Execute the query.
mysqlx::Result res = stmt.execute();
Get query results.
for (auto row : res.fetchAll()) { std::cout << row[0].get<std::string>() << std::endl; }
Using ODBC
Include the necessary ODBC header files.
#include <iostream> #include <sql.h> #include <sqlext.h>
Establish a database connection.
SQLHENV henv; SQLHDBC hdbc; SQLAllocEnv(&henv); SQLAllocConnect(henv, &hdbc); SQLDriverConnect(hdbc, nullptr, "DSN", SQL_NTS, nullptr, 0, nullptr, SQL_DRIVER_NOPROMPT);
Create a SQL statement handle.
SQLHSTMT hstmt; SQLAllocStmt(hdbc, &hstmt);
Set SQL statement.
std::string sql = "SELECT * FROM table_name WHERE column_name = ?"; SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 0, 0, nullptr, 0, nullptr);
Bind cin input to a SQL statement.
std::string input; std::cin >> input; SQLSetParam(hstmt, 1, SQL_C_CHAR, input.c_str(), input.length(), nullptr);
Execute SQL statement.
SQLExecute(hstmt);
Get query results.
SQLBindCol(hstmt, 1, SQL_C_CHAR, nullptr, 0, nullptr); while (SQLFetch(hstmt) == SQL_SUCCESS) { char buffer[1024]; SQLGetData(hstmt, 1, SQL_C_CHAR, buffer, sizeof(buffer), nullptr); std::cout << buffer << std::endl; }
The above is the detailed content of How to combine cin and database in c++. For more information, please follow other related articles on the PHP Chinese website!