2

The codes below inserts values into MYSQL database. If i use "sprintf(Query, "INSERT into t(d) values (%c)", a);" it wont insert the word hello into my database. i have also tried using (%s) in the above statement. However, if i use "sprintf(Query, "INSERT into t(d) values (%d)", b);" it inserts the values 1234 into the database.

What is happening? Why wont it insert character's or string into my database but only integers?

The column d is my database is defined as char type.

Thanks.

#include "stdafx.h"
#include <stdio.h>
#include <mysql.h> 
//#include <string>
//using std::string;
//#include <atlstr.h>

MYSQL *pConnection;
MYSQL_RES *pResult=NULL; 
MYSQL_ROW Row;
char Query[256];

int main(int argc, char* argv[])
{
    pConnection = mysql_init(NULL);

    mysql_real_connect(pConnection,"localhost","root","y123","test",0,NULL,0); 

char a[] ="Hello"; 
int b = 1234;
printf("%s", a);

sprintf(Query, "INSERT into t(d) values (%s)", a);
mysql_query(pConnection, Query);

}   
1
  • What types is you column You trying to insert? Commented Mar 12, 2012 at 14:20

2 Answers 2

4

You still need to write properly formatted queries. Yours is lacking strings around the inserted value:

sprintf(Query, "INSERT into t(d) values ('%s')", a);
                                         ^--^-- missing

Your version was generating something like

INSERT INTO t(d) values (foo);

almost certainly your table does not have a field named foo, so the query would fail and return a 'false' value. Since you had no error checking whatsoever, you'd never have noticed things were failing.

NEVER assume a query succeeds. ALWAYS check return values for success/failure. Even if your SQL is 100% perfect and valid, it can still fail for any number of other reasons.

Sign up to request clarification or add additional context in comments.

Comments

2

SQL strings needs to be inside single quotes:

sprintf(Query, "INSERT into t(d) values ('%s')", a);
// Note the single quotes ---------------^--^

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.