如何使用C ++在数据库中插入数据 [英] How to insert data in database using C++

查看:293
本文介绍了如何使用C ++在数据库中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用 namespace std;

MYSQL mysql,* connection;
MYSQL_RES结果;
MYSQL_ROW行;

char * ip =( char *) 192.168.49.131;
char * usr =( char *) root;
char * pass =( char *) admin;
char * db =( char *) vcs;

int query_state;

int main( int argc, char ** argv)
{
mysql_init(& mysql);

connection = mysql_real_connect(& mysql,ip,usr,pass,db, 0 ,NULL, 0 );

if (connection == NULL)
{
cout<< mysql_error(& mysql)< < ENDL;
}

else
{
(mysql_query(& mysql, INSERT into'vcs'。'users'('id','fname','sname')VALUES('3','rana' ,'sameer')));
if (query_state!= 0 ){
cout<< mysql_error(连接)<< ENDL;
return 1 ;
}
}
mysql_close(& mysql);

}





我使用此代码与我的phpmyadmin sql建立连接

我成功了。

但是我的数据库中没有输入以下数据。

我该怎么办?

解决方案

我会尝试传递连接而不是& mysql mysql_query 功能。



祝你好运

Espen Harlinn


我认为插入后缺少提交。你可以尝试一个querry来创建表(因为creatin表不需要提交)。如果它的工作意味着你错过了以提交querry结束你的代码。


你的查询错了,你写了如下的查询:



  INSERT  进入 '  vcs''  users''  id' '  fname''  sname' VALUES '  3''  rana'' < span class =code-string> sameer')





将您的查询更改为:



  INSERT  进入`vcs` .users`(`id`,`fname`,` sname`) VALUES '  3''  rana'' 萨米尔'


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

using namespace std;

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

char * ip = (char*)"192.168.49.131";
char * usr = (char*)"root";
char * pass = (char*)"admin";
char * db = (char*)"vcs";

int query_state;

int main (int argc, char **argv)
{
	mysql_init(&mysql);

	connection = mysql_real_connect(&mysql, ip, usr, pass, db, 0, NULL, 0);

	if (connection==NULL)
	{
		cout<<mysql_error(&mysql)<<endl;
	}

	else
	{
		(mysql_query(&mysql, "INSERT into 'vcs'.'users' ('id', 'fname', 'sname') VALUES ('3', 'rana', 'sameer')"));
		if (query_state !=0) {
		cout << mysql_error(connection) << endl;
		return 1;
		}
	}
	mysql_close(&mysql);

}



I am using this code for establish the connection with my phpmyadmin sql
and I get succeed.
but the following data is not entered in my database.
how can I do this???

解决方案

I''d try to pass connection and not &mysql to the mysql_query function.

Best regards
Espen Harlinn


I think it''s a lack of commit after insertion. Could you try a querry for creating tables (as creatin tables does not require a commit). if it works that mean that u miss to end your code with a commit querry.


Your query is wrong, you wrote your query like below:

INSERT into 'vcs'.'users' ('id', 'fname', 'sname') VALUES ('3', 'rana', 'sameer')



Change your query to below:

INSERT into `vcs`.`users` (`id`, `fname`, `sname`) VALUES ('3', 'rana', 'sameer')


这篇关于如何使用C ++在数据库中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆