Home >Backend Development >C++ >How to combine cin and database in c++
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.
<code class="cpp">#include <iostream> #include <mysqlx/xdevapi.h></code>
Establish a database connection.
<code class="cpp">mysqlx::Session session("host", "port", "user", "password", "database");</code>
Create query statement.
<code class="cpp">std::string query = "SELECT * FROM table_name WHERE column_name = ?";</code>
Bind cin input to query parameters.
<code class="cpp">mysqlx::PreparedStatement stmt = session.prepare(query); std::string input; std::cin >> input; stmt.bind("column_name", input);</code>
Execute the query.
<code class="cpp">mysqlx::Result res = stmt.execute();</code>
Get query results.
<code class="cpp">for (auto row : res.fetchAll()) { std::cout << row[0].get<std::string>() << std::endl; }</code>
Using ODBC
Include the necessary ODBC header files.
<code class="cpp">#include <iostream> #include <sql.h> #include <sqlext.h></code>
Establish a database connection.
<code class="cpp">SQLHENV henv; SQLHDBC hdbc; SQLAllocEnv(&henv); SQLAllocConnect(henv, &hdbc); SQLDriverConnect(hdbc, nullptr, "DSN", SQL_NTS, nullptr, 0, nullptr, SQL_DRIVER_NOPROMPT);</code>
Create a SQL statement handle.
<code class="cpp">SQLHSTMT hstmt; SQLAllocStmt(hdbc, &hstmt);</code>
Set SQL statement.
<code class="cpp">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);</code>
Bind cin input to a SQL statement.
<code class="cpp">std::string input; std::cin >> input; SQLSetParam(hstmt, 1, SQL_C_CHAR, input.c_str(), input.length(), nullptr);</code>
Execute SQL statement.
<code class="cpp">SQLExecute(hstmt);</code>
Get query results.
<code class="cpp">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; }</code>
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!