Untitled
unknown
c_cpp
a year ago
1.2 kB
7
Indexable
#include <iostream>
#include <memory>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
int main() {
try {
// Initialize driver
sql::Driver* driver = get_driver_instance();
// Create a connection
std::unique_ptr<sql::Connection> con(driver->connect("tcp://127.0.0.1:3306", "user", "password"));
// Connect to the MySQL test database
con->setSchema("testdb");
// Create a prepared statement
std::unique_ptr<sql::PreparedStatement> pstmt(con->prepareStatement("INSERT INTO test_table(name, age) VALUES (?, ?)"));
// Set the parameters
pstmt->setString(1, "John Doe");
pstmt->setInt(2, 30);
// Execute the query
pstmt->executeUpdate();
std::cout << "Insert successful." << std::endl;
} catch (sql::SQLException& e) {
std::cerr << "SQLException: " << e.what() << std::endl;
std::cerr << "MySQL error code: " << e.getErrorCode() << std::endl;
std::cerr << "SQLState: " << e.getSQLState() << std::endl;
}
return 0;
}
Editor is loading...
Leave a Comment