无法从C ++中插入MySQL中的数据

时间:2014-05-30 10:47:16

标签: c++ mysql

我试图在mysql数据库表中插入来自C ++控制台应用程序的数据。

我有桌子:

CREATE TABLE `Emp` (
  `empId` int(11) NOT NULL AUTO_INCREMENT,
  `empName` varchar(50) NOT NULL,
  PRIMARY KEY (`empId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

现在当我尝试插入数据时,我收到了成功消息,但是当我在数据库中交叉检查时,我没有得到任何结果。

这是我给插入输入的内容:

crazydeveloper@crazydeveloper:~/Desktop$ g++ InsertInMysql.cpp -o InsertInMysql -L /usr/include/mysql -lmysqlclient -I /usr/include/mysql
crazydeveloper@crazydeveloper:~/Desktop$ ./InsertInMysql

Please Enter Your Name: 
Maddy
Connection Established Successfully.......
Connection Established Successfully.......
Your Name is Maddy
INSERT INTO Emp VALUES('Maddy')
Success....

更新 当我为empName插入2个单词时,只插入第一个单词:

这里是查询

Please Enter Your Name: 
Brett Lee
Connection Established Successfully.......
Connection Established Successfully.......
Your Name is Brett
INSERT INTO Emp(empName) VALUES('Brett')

这是我的C ++源代码:

#include <iostream>
#include <mysql.h>
#include <my_global.h>

#define SERVER "localhost"
#define USERNAME "root"
#define PASSWORD "root"
#define DATABASE "Test"

using namespace std;

int main() {

    string empFirstName, query;
    int res;

    cout << "\nPlease Enter Your Name: " << endl;
    getline(cin, empFirstName);

    MYSQL *connect;
    connect = mysql_init(NULL);

    if (connect){
        cout << "Connection Established Successfully......." << endl;
    }

    connect = mysql_real_connect(connect, SERVER, USERNAME, PASSWORD, DATABASE, 0,NULL,0);

    if (connect){
        cout << "Connection Established Successfully......." << endl;
        cout << "Your Name is " << empFirstName << endl;
    }

    query = "INSERT INTO Emp VALUES('"+empFirstName+"')";

    cout << query << endl;

    if (mysql_query(connect, query.c_str())){
        cout << "Success.... \n" << endl;
    }   

    mysql_close (connect);

    return 0;   
}

发现错误

刚发现错误: 当我没有在查询中提供列名empName时,会打印成功消息。现在,当我提供列名empName时,不会打印成功消息。

要插入的查询:

// prints success message
query = "INSERT INTO Emp VALUES('"+empFirstName+"')";

要插入(更新后)的查询:

// does not prints success message
query = "INSERT INTO Emp(empName) VALUES('"+empFirstName+"')";

请指导我哪里弄错了。感谢。

1 个答案:

答案 0 :(得分:0)

您的表格结构表明它有一个主键empId作为第一列。

所以当您将查询写为

INSERT INTO Emp VALUES ('first name')

该值将引用列empId,查询将失败。

在这种情况下,您需要明确指定列名称,例如

INSERT INTO Emp (empName) VALUES ('first name')

现在mysql知道该值是列empName。