linux-mysql-insert1

//simple_mysql_insert.c

#include 
#include 
#include 


int main(int argc, char *argv[]){

	MYSQL my_connection;
	mysql_init(&my_connection);

	const char* host = "localhost";
	const char* user = "root";
	const char* password = "!QAZ2wsx";
	const char* dbname = "rick";

	if(argc==2){
		password = argv[1];
	}

	int ret = -1;

	MYSQL*  conn_ptr= mysql_real_connect(&my_connection ,host, user, password,dbname,0,NULL,0);

	if(conn_ptr){

		printf("Connection succeed!\n");

		const char* sql = "insert into children(fname, age) values('Kinder', 10)";
		ret = mysql_query(&my_connection, sql);
		if(!ret){
			printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(&my_connection));
		}else{
			fprintf(stderr, "Insert error %d : %s \n", mysql_errno(&my_connection), mysql_error(&my_connection));
		}
		mysql_close(&my_connection);

	}else{

		fprintf(stderr, "Connection failed!\n");
		if(mysql_errno(&my_connection)){
			fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection));
		}
	}
	return 0;
}

运行:

xx@ubuntu:~/workspace/mysql-test$ g++ -o test-insert simple_mysql_insert.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
xx@ubuntu:~/workspace/mysql-test$ ./test-insert
Connection succeed!
Inserted 1 rows


你可能感兴趣的:(Linux,数据库)