简体   繁体   中英

Unexpected error in connecting c++ program with mysql

I am developing a c++ console application in visual C++ 2010 that is required to connect to mySQL database. I am using wamp server for mysql and mySQL C++ connector to connect. Code works fine for reading database but when I try to Insert data, it gives unexpected error. Any one had such an experience?

Here is my full code: (Output of the code is: "SQL Error: Error Message: Unknown Exception")

    // Standad C++ includes
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

// Include the Connector/C++ headers
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
#include "cppconn/sqlstring.h"

// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")

// Specify our connection target and credentials
const string server   = "tcp://127.0.0.1:3306";
const string username = "cashif";
const string password = "111222"; // No password - NEVER DO THIS ON A PRODUCTION SERVER!

int main()
{
    sql::Driver     *driver; // Create a pointer to a MySQL driver object
    sql::Connection *dbConn; // Create a pointer to a database connection object
    sql::Statement  *stmt;   // Create a pointer to a Statement object to hold our SQL commands
    sql::ResultSet  *res;    // Create a pointer to a ResultSet object to hold the results of any queries we run

    // 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 dengue_test");              // Select which database to use. Notice that we use "execute" to perform a command.

        stmt->execute("insert into patients values(3,\"Amina\",\"Iqbal Town\""); // Perform a query and get the results. Notice that we use "executeQuery" to get results back
    }
    catch (sql::SQLException e)
    {
        cout << "SQL error. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    // While there are still results (i.e. rows/records) in our result set...
/*
    while (res->next())
    {
        // ...get each field we want and output it to the screen
        // Note: The first field/column in our result-set is field 1 (one) and -NOT- field 0 (zero)
        // Also, if we know the name of the field then we can also get it directly by name by using:
        // res->getString("TheNameOfTheField");
        cout << res->getString(1) << " - " << res->getString(2) << " - " << res->getString(3) << endl;                
    }
    */
    // Clean up after ourselves
    //delete res;
    delete stmt;
    delete dbConn;

    system("pause");
    return 0;
}

You have two errors in your SQL, one that MySQL will let you get away with and one that it won't. You're also picking up a bad habit.

Both bugs are right here:

stmt->execute("insert into patients values(3,\"Amina\",\"Iqbal Town\"");

String literals in SQL use single quotes, not double quotes; MySQL will let you get away with this though. But, you also have a missing closing parenthesis and MySQL doesn't like that one bit. You should say this:

stmt->execute("insert into patients values(3, 'Amina', 'Iqbal Town')");

Not specifying the columns in an SQL INSERT is a bad habit so you should be saying this:

insert into patients (col1, col2, col3) values (...)

where col1 and friends are, of course, the real column names. Columns in tables don't have any well defined order so you should be specific to avoid interesting bugs and maintenance nightmares.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM