I'm trying to get some user data into an INSERT query using the Mysql C API (don't know if this belongs rather in the Mysql forum, let me know...)

I have the following code taking some pointers from the Mysql webpage forum, but to no avail:

#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>


int main() 
{ 
	char *server = "localhost";
   	char *user = "root";
   	char *password = /* password to acces mysql */;	
	char *database = "palabra";	

	
	char Name[] = "test"; 
	char *cmd; 
	cmd=malloc(1024); 

	sprintf(cmd, "INSERT INTO prueba VALUES(%s)", Name); 
	MYSQL *conn; 

	conn=mysql_init(NULL); 
	mysql_real_connect(conn, server, user, password, database, 0, NULL, 0);
	mysql_query(conn, "INSERT INTO prueba VALUES(Name)"); 
	mysql_close(conn); 
	return 0; 
}

The code compiles without error, but the table is unchanged with nothing inserted to it.
More over, I don't really know the sprintf part too well, or why it's used (like I said I took pointers from other forums just to try stuff), since it's not used later when the mysql_query() is called.

T

Recommended Answers

All 3 Replies

My guess is that VALUES strings must be surrounded with single-tick quotes (unshifted double quotes on my keyboard). sprintf(cmd, "INSERT INTO prueba VALUES('%s')", Name);

My guess is that VALUES strings must be surrounded with single-tick quotes (unshifted double quotes on my keyboard). sprintf(cmd, "INSERT INTO prueba VALUES('%s')", Name);

That was it, thanks!

I also changed the

mysql_query(conn, "INSERT INTO prueba VALUES(Name)");

to

mysql_real_query(conn, cmd, (unsigned int)strlen(cmd));

>>(unsigned int)strlen(cmd)

The typecase is not necessary because strlen() returns unsigned int.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.