插入MYSQL db中的表后出现错误消息

时间:2018-02-16 20:33:03

标签: c++ mysql

我有这个c ++代码可以正常工作,我可以从表中读取并写入表:

int main()

{


    // Try to get a driver to use to connect to our DBMS
    try
    {
        driver = get_driver_instance();
    }
    catch (sql::SQLException e)
    {
        cout << "Could not get a database driver. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    // Try to connect to the DBMS server
    try
    {
        dbConn = driver->connect(server, username, password);
    }
    catch (sql::SQLException e)
    {
        cout << "Could not connect to database. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    stmt = dbConn->createStatement(); // Specify which connection our SQL statement should be executed on

    // Try to query the database
    try
    {
        stmt->execute("USE test");  // Select which database to use. Notice that we use "execute" to perform a command.

        res = stmt->executeQuery("INSERT INTO users (fName, lName, age) VALUES ('fname', 'lname', 25)"); // Perform a query and get the results. Notice that we use "executeQuery" to get results back
        //res = stmt->executeQuery("SELECT * FROM users");
        //return 0;
    }
    catch (sql::SQLException e)
    {
        cout << "SQL error. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }


    sql::ResultSetMetaData *res_meta = res -> getMetaData();
    int columns = res_meta -> getColumnCount();


    // While there are still results (i.e. rows/records) in our result set...
    while (res->next())
    {

        for (int i = 1; i <= columns; i++) {
                cout << res->getString(i) << " | " ;
                }
         cout << endl;
    }

    delete res;
    delete stmt;
    delete dbConn;
    //system("pause");
    return 0;
}

因此,这会插入到表中,但后来我收到此错误消息

  

SQL错误。错误讯息:sh:1:暂停:未找到

如果我使用&#34;选择&#34;这不会发生。

我也知道这个问题已被问过here但不幸的是它没有答案所以我再次提问。

2 个答案:

答案 0 :(得分:2)

INSERT不是查询。尝试使用executeUpdate()而不是executeQuery()。查看官方MySQL示例here

替换此行

res = stmt->executeQuery("INSERT INTO users (fName, lName, age) VALUES ('fname', 'lname', 25)"); // Perform a query and get the results. Notice that we use "executeQuery" to get results back

使用以下行(您可能需要一个新的.h文件):

sql::PreparedStatement *pstmt;

pstmt = con->prepareStatement("INSERT INTO users (fName, lName, age) 
VALUES ('fname', 'lname', 25)");
res = pstmt->executeUpdate();
delete pstmt;

您也可以尝试使用execute(),如this Stackoverflow问题所示。函数execute()用于通用SQL命令,但在返回值中可能不像更多指定函数那样冗长(它返回一个布尔值)。

答案 1 :(得分:2)

您的问题与MySQL Query executes but throws exception相关。

executeQuery()假设sql查询应返回sql::ResultSet,但您的INSERT INTO查询不会。您可以使用execute()代替,返回true或false:

try
{
    stmt->execute("USE test");
    stmt->execute("INSERT INTO users (fName, lName, age) VALUES ('fname', 'lname', 25)");
}
catch (sql::SQLException e)
{
    cout << "SQL error. Error message: " << e.what() << endl;
    exit(1);
}