【问题标题】:How can i insert values into database(mySql) using cpp program?如何使用 cpp 程序将值插入数据库(mySql)?
【发布时间】:2016-11-23 08:06:32
【问题描述】:
void SignUp()
{
  MYSQL* conn; 
  MYSQL_ROW row;
  MYSQL_RES* res;
  int nQueryState = 0;
  int nId         = 0;
  char szName[45];
  char szPassWord[45];
  char szQuestion[45];
  char szPhone[45];

  cout<<"Enter the Id";
  cin>>nId;

  cout<<"Enter the Name";
  cin>>szName;

  cout<<"Enter the Password";
  cin>>szPassWord;

  cout<<"Enter the Question";
  cin>>szQuestion;

  cout<<"Enter the Phone";
  cin>>szPhone;

 conn = mysql_init(0);
 conn =mysql_real_connect(conn,"localhost","root","12356","hari",0,NULL,0);
nQueryState = mysql_query(conn,"insert into  userdetails values(nId,szName,szPassword,szQuestion,szPhone)");

if(0!=nQueryState)
{
    cout<<"\n\nConnection not Established";
}
}

我想在名为 userdetails 的表中输入详细信息。它给了我一个输出,使得连接没有建立。请通过它并帮助我。我正在使用代码块 ide 和 mySql5.1

【问题讨论】:

  • 您应该添加一些错误检查,例如检查mysql_initmysql_real_connect 是否不返回空指针。
  • Insert 没有指定userdetails 表的列名,这在某些情况下可能是个问题。检查mysql_query是否报错并打印。

标签: c++ mysql


【解决方案1】:

尝试如下:

MYSQL mysql,*connection;
MYSQL_RES result;
MYSQL_ROW row;


mysql_init(&mysql);
connection =mysql_real_connect(&mysql,"localhost","root","12356","hari",0,NULL,0);

if (connection==NULL)
{
    cout<<mysql_error(&mysql)<<endl;
}
else{
    nQueryState = mysql_query(&mysql,"insert into  userdetails values('"+nId+"','"+szName+"','"+szPassword+"','"+szQuestion+"','"+szPhone+"')");

  if (nQueryState !=0) {
    cout << mysql_error(connection) << endl;
    return 1;
  }
}

mysql_close(&mysql);

参考:http://www.codeproject.com/Questions/337901/How-to-insert-data-in-database-using-Cplusplus

【讨论】:

  • 这里显示一个错误,例如 szname 不是一个字段。实际上字段名称是名称。我想将存储在 szName 中的用户输入插入到数据库中。请帮助。提前致谢
  • 我更改了插入查询。请检查一下。
  • 我更改了插入查询。但它显示了一个语法错误,例如:“'const char*'和'const char [4]'类型的无效操作数到二进制'operator+'|”。请帮我避免这个错误。提前感谢
猜你喜欢
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2015-06-18
  • 2016-02-07
  • 2013-12-18
相关资源
最近更新 更多